[java2] #28 - identityHashCode, concat
System.identityHashCode()
: 객체의 고유한 HashCode를 리턴하는 메서드이다. System클래스에 정의되며 오버라이딩 할 수 없고, 전달된
객체의 hashcode를 int로 리턴한다.
HashCode()
: 모든 객체의 부모 클래스인 Object 클래스에 정의 되어있기 때문에 하위 클래스들이 오버라이딩 할 수 있다.
또한 String 클래스에선 value로 hashCode를 만들고 있기 때문에 object가 달라도 문자열이 같으면 동일한
hashCode를 리턴하게된다.
String str1 = "JAVA";
String str2 = "JAVA";
String str3 = new String("JAVA");
//1
System.out.println("str 1 hashCode : " + str1.hashCode()); //2269730
System.out.println("str 2 hashCode : " + str2.hashCode()); //2269730
System.out.println("str 3 hashCode : " + str3.hashCode()); //2269730
//2
System.out.println("str 1 hashCode : " + System.identityHashCode(str1)); //1995265320
System.out.println("str 2 hashCode : " + System.identityHashCode(str2)); //1995265320
System.out.println("str 3 hashCode : " + System.identityHashCode(str3)); //1746572565
1. String 클래스에서 문자열이 같으면 동일한 hashCode를 리턴한 것을 확인할 수 있다.
2. 값이 아닌 객체를 비교할 땐 identityHashCode()를 사용하는것이 적절하다는 것이 잘 알려진 내용이지만 위와 같이
저장한 값이 같으면 동일한 고유값이 리턴되는걸 볼 수 있다.
void new연산자() {
Member member = new Member("hello", "1");
Member member2 = new Member("world", "2");
Member member3 = new Member("hello", "1");
//1
System.out.println(System.identityHashCode(member)); //646204091
System.out.println(System.identityHashCode(member2)); //445010547
System.out.println(System.identityHashCode(member3)); //680306160
//2
System.out.println(member.hashCode()); //-1220935265
System.out.println(member2.hashCode()); //-782084384
System.out.println(member3.hashCode()); //-1220935265
}
record Member(
String name,
String id
) {
}
1. 전의 경우 같은 유형과 값이면 같은 hashcode를 리턴했다. 하지만 member객체를 생성하고 값을 넣은 경우
같은 값("hello","1")이지만 모두 다 다른 객체 고유 hashcode가 리턴된 것을 확인할 수 있다.
2. HashCode()는 Object 클래스에 정의된 것을 출력하기 때문에 위의 다른 예시와 똑같이 같은 값이면 동일한 hashcode를 리턴하는것을 확인할 수 있다.
concat
문자열을 합칠 때 +, append, concat을 사용한다. 하지만 가끔 +연산자로 합친 문자열을 (String) ""처럼
형변환 해주는 경우가 있다. 그럼 연산자로 합치는 것과 메서드를 사용하는것은 무슨 차이일까
+ 연산자
- String 객체는 불변이기 때문에 각각 합칠 때마다 새로 메모리에 할당된다. 여러 문자열을 합친다고
하면 과도하게 메모리를 차지하게 된다. - 편리하지만 성능은 좋지 않은 방식이다.
- java 1.6 부터는 StringBuilder, StringConcatFactory 또는 StringBuffer을 이용해 문자열을 변환시킨 뒤,
append로 문자열을 더하고 다시 toString 함수로 문자열을 반환해준다.
String a = "concat과 "
String b = "append의 차이"
System.out.println(a + b);
// concat과 append의 차이
concat
- concat은 합친 문자열을 new String()해서 생성해준다.
- StringBuilder는 append()로 문자열을 합칠 수 있다. String으로 합치는 것과 다른 점은 immutable인 String
은 수정하려면 String을 다시 대입해야 하지만, StringBuilder는 메모리 할당 과정 없이 수정 가능하다. - StringBuffer는 StringBuilder와 호환 가능하지만 thread-safe하고 StringBuilder는 동기화를 보장하지 않는다.
- single thread - StringBuilder
multi thread - StringBuffer
String a = "concat과 "
String b = "append의 차이"
System.out.println(a.concat(b));
// concat과 append의 차이
여러 개의 문자열을 더할 때는 +연산자, 두 개의 문자열을 더할 때는 concat
참고: https://infjin.tistory.com/43?category=999286