본문 바로가기
반응형

IT/Java394

try-with-resources (AutoCloseable) 기존에 Try Catch 문을 사용할 경우파일을 열거나 특정 url 등을 열거나 할 경우 종료 이후에 close를 반드시 해줘야만 했다. 그렇지 못할 경우에는 자원의 낭비가 생기고 심하게는 서버가 죽을 경우도 있다. 예를들어 코드가 아래와 같다.try{     ..이상 생략     BufferedReader reader = new BufferedReader(new InputStreamReader(url));     ..이하 생략} catch (MalformedURLException e) {     reader.close();      e.printStackTrace();     throw e;} 혹은 finally 로 묶어서 닫아주고는 한다.try{     ..이상 생략     BufferedReader.. 2024. 8. 5.
[ArrayList] 조건 삭제를 위한 removeIf ArrayList 내에 값들중 특정 값을 삭제하기 위한 코드는 아래와 같다.(반복문 구현)..이상 생략for (Integer value : list){     if (value > 10){          list.remove(value);     }}..이하 생략 이렇게 반복문을 돌면서 특정 값을 지워줘야한다. 하지만 자바8부터 생긴 removeIf를 사용하면 람다식을 이용하여 간단하게 삭제할 수 있다. 위 코드를 아래와 같이 변경이 가능하다.list.removeIf(value -> value>10); 이렇게 간단하게 1줄로 변경이 가능하다. 2024. 8. 2.
[Error] incompatible types / Type mismatch 아래와 같은 에러가 발생하였다. [Java] java: incompatible types: byte[] cannot be converted to byte 그밖에도 다양하게 에러는 발생할 수 있다.ex>incompatible types: String cannot be converted to booleanincompatible types: String cannot be converted to Integer 형 변환이 불가능하다는 의미이고,형태를 변경해주면 해결된다. 비슷하게 컴파일에 나올수 있는 에러로 Type mismatch: cannot convert from element type Integer to ArrayList 이런 에러도 있다. 동일하게 형태가 변경이 불가능하다는 의미로 위와 동일하게 해결 가.. 2024. 8. 1.
[Error] ConcurrentModificationException ConcurrentModificationException은 보통 Collections 에서 리스트, 맵 등에서 제거하고 난 후에 발생한다. 예를들어 리스트가 크기가 10이라서 ..이상 생략for (int i=0;i      System.out.println(list[i]);..이하 생략으로 반복문을 돌릴때 리스트의 i번째를 가져온다.마지막으로 가면 10번째의 값을 가져와야하는데 그전에 만약 remove를 했다면 list의 길이는 10이 아니게 된다.그럴 경우에 발생하는 에러이다. 해결방법- for loop에서 역순으로 순회하면서 삭제Array일 경우에 가능하고 0부터올리는것이 아닌 10부터 내려오는 방법이다...이상 생략for (int i=list.size();i>=0; i--){     System.o.. 2024. 7. 31.
HashMap 정렬(Key/Value) map에 대해서는 아래 참고 포스팅 참고 바란다. Map을 Key기준으로 정렬하기 위해서는 아래 코드와 같이 해결이 가능하다...이상 생략/ map 선언 되어있음List keySet = new ArrayList(map.keySet());// 키 값으로 오름차순 정렬Collections.sort(keySet);Collections에 대해서는 참고 포스팅 참고 바란다. Value 기준 정렬은 아래와 같다.Map map = new HashMap();map.put("a", 1);map.put("b", 3);map.put("c", 6);map.put("d", 9);map.put("e", 2);List keySetList = new ArrayList(map.keySet());// 오름차순System.out.prin.. 2024. 7. 29.
Collections 함수에 대해 자바에서 List를 정렬하는 방법에 대해서는 간단히 sort 를 사용하여 가능하다.Arrays.sort();Arrays.sort(list);https://docs.oracle.com/javase/8/docs/api/ Java Platform SE 8 docs.oracle.com 그리고 또 다른방법으로는 Collections 를 사용하면 된다. https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html Collections (Java Platform SE 8 )Rotates the elements in the specified list by the specified distance. After calling this method, the el.. 2024. 7. 28.
String / StringBuffer,StringBuilder 차이 이전 포스팅에서 문자열 합치기 관련해서 StringBuffer,StringBuilder 에 대해 다룬 글이 있다.자세한 내용은 아래 참고 포스팅 참고 바란다. 우선 포스팅의 결론을 먼저 말하면String과 StringBuffer/StringBuilder의 차이점은 String은 immutable(불변), StringBuffer는 mutable(변함)에 있다. 좀더 부연설명을 하면StringString 객체는 한번 생성되면 할당된 메모리 공간이 변하지 않음새로운 String 객체를 만든 후, 새 String 객체에 연결된 문자열을 저장하고, 그 객체를 참조하도록 함이런 이유들로 문자열 연산이 많은 경우엔 비효율적이다. StringBuffer,StringBuilder 문자열 연산 등으로 기존 객체의 공간이 .. 2024. 7. 25.
List와 ArrayList Java 에서 흔히 사용되는 List와 ArrayList에 대해서 작성해보려고 한다. 사용법에 대해서는 굳이 설명은 하지 않고,둘의 차이에 대해서 알아보려고 한다. 우선 public List method(){..이상 생략     ArrayList list = new ArrayList();     return list;..이하 생략}이런 식으로 메서드를 구현하면 에러가 안난다. 분명 Return 형식은 List이고 실제 Return 은 ArrayList 인데 말이다. 정답은 ArrayList는 List를 implements 하고 있기 때문이다.public class ArrayListE> extends AbstractListE>        implements ListE>, RandomAccess, Clon.. 2024. 7. 24.
[Error] Failed to parse configuration class springboot run  기동시 아래와 같은 에러가 발생하였다. Failed to parse configuration class [com.test.TestProjectApplication] 그리고 아래에 이어서 이렇게 나와있다.Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'testController' for bean class [com.test.restapitest.controller.TestController] conflicts with existing, non-compatible bean definition of same name an.. 2024. 7. 23.
반응형