hashCode()
- 객체의 주소를 기준으로 객체를 식별할 수 있는 정수 코드 리턴
- String은 재정의 되어 내용 값을 기준으로 식별 값을 리턴 (참조 값이 같으면 같은 hashCode)
public class StringTest {
public static void main(String[] args) {
String str1 = "Kitty";
String str2 = "Kitty";
String str3 = new String("Kitty");
String str4 = new String("Kitty");
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(str3.hashCode());
System.out.println(str4.hashCode());
/*
* 출력 값
* 72507323
* 72507323
* 72507323
* 72507323
*
*/
}
}
String의 == equals
- ==는 주소값을 비교
- equals는 참조값(내용) 비교
public class StringTest {
public static void main(String[] args) {
String str1 = "Kitty";
String str2 = "Kitty";
String str3 = new String("Kitty");
String str4 = new String("Kitty");
System.out.println(str1==str2);
System.out.println(str2==str3);
System.out.println(str3==str4);
/*
* 출력 값
* true
* false
* false
*/
System.out.println(str1.equals(str2));
System.out.println(str2.equals(str3));
System.out.println(str3.equals(str4));
/*
* 출력 값
* true
* true
* true
*/
}
}
자바에서의 String 객체 메모리 관리
String str1 = "Kitty";
String str2 = "Kitty";
자바 힙영역의 String Constant Pool에 값이 저장되고 같은 리터럴은 같은 주소값을 갖게 된다.
반면
String str3 = new String("Kitty");
String str4 = new String("Kitty");
힙 메모리에 개별 객체가 만들어진다.
'기술면접대비' 카테고리의 다른 글
[JAVA] 클래스/객체/인스턴스 (0) | 2020.08.25 |
---|---|
[JAVA]오버로딩(Overloading) / 오버라이딩(Overriding) (0) | 2020.08.24 |
[JAVA] StringTokenizer와 String split() 차이 (0) | 2020.08.21 |
[Web] HTTP Request Method /GET과 POST 비교 (0) | 2020.08.20 |
[Web] REST, REST API, RESTFUL의 모든것 (0) | 2020.08.19 |