Verity's Daily Logs_

[JAVA]String의 equals(), hashCode() 본문

JAVA

[JAVA]String의 equals(), hashCode()

johye0 2022. 2. 8. 22:35
반응형

String의 equals(), hashCode()


String은 재정의한 equals(), hashCode()를 가지고 있다.

일반 Object class의 equals(), hashCode()는 아래 글 참조

https://hye0-log.tistory.com/48

 

[JAVA]Object (equals, hashCode ...)

Class Object "Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class." java.lang 패키지 중에서도..

hye0-log.tistory.com

 

equals()

문자열을 char 단위로 한 글자씩 모두 비교하여 동일하면 true를 리턴한다.

⇒ 서로 다른 객체라도 같은 문자열을 가지고 있으면 동일하다고 판단된다.

 

hashCode()

문자열에서 한 글자씩 가져와서 정수값으로 변경하는 메서드.

⇒ 객체의 주소 값으로 hashCode를 생성하는 것이 아니라 다른 String객체도 문자열이 같으면 hashCode가 같다.

⇒ 객체의 찐 주소를 알고 싶다면 System.identityHashCode() 메서드를 사용하면 된다.

 

public class ObjectTests {

    public static void main(String[] args) {
        ObjectTests objectTests = new ObjectTests();

        objectTests.equalsForString();
    }

    private void equalsForString() {
        String name1 = "Hailey";
        String name2 = "Hailey";
        String name3 = new String("Hailey");
        System.out.println("name1 = " + name1.hashCode() + ", " + System.identityHashCode(name1));
        System.out.println("name2 = " + name2.hashCode() + ", " + System.identityHashCode(name2));
        System.out.println("name3 = " + name3.hashCode() + ", " + System.identityHashCode(name3));

        /**
         * String values are compared using '==', not 'equals()'
         *  Inspection info: Reports any use of == or != to compare strings, which compares object identity.
         *  In most cases strings should be compared with an equals() call instead,
         *  which does a character-by-character comparison when the strings are different objects.
         */
        System.out.println(name1 == name2);
        System.out.println(name1 == name3);

        /**
         * Result of 'name1.equals(name2)' is always 'true'
         * Compares this string to the specified object.
         * The result is true if and only if
         * the argument is not null and is a String object that represents the same sequence of characters as this object.
         */
        System.out.println(name1.equals(name2));
        System.out.println(name1.equals(name3));


        /**
         * 출력 :::
         * name1 = 1749861, 7468253
         * name2 = 1749861, 7468253
         * name3 = 1749861, 14655327
         * true
         * false
         * true
         * true
         */
    }
}

 

 

String 변수의 생성


String은 문자열 객체의 인스턴스 주소를 담고 있는 참조형 변수이다. 따라서 String은 생성 방식에 따라 생성되는 메모리 영역이 달라지게 된다.

 

리터럴 생성

  • str 변수는 stack 메모리에, "Hello"라는 값은 Heap 메모리 내에 String pool이라는 곳에 저장되고, 그 주소가 str 변수에 저장된다.
  • String pool에 저장이 될 때는 intern() 메서드가 실행이 되게 되는데, 같은 값이 있을 경우 기존 값의 메모리 주소를, 다른 값일 경우 새롭게 객체를 생성해 값을 저장하고 그 메모리 주소를 리턴한다. ⇒ String pool 이 HashMap 자료구조 형태이기 때문에 나타나는 특성이다.
  • String a = "Hello";
    String b = "Hello";
    boolean c = a == b;
    System.out.println(c);   //true, a와 b의 주소 값이 같음.

 

 

new 연산자 생성

  • new 연산자를 사용해 생성한 경우 str이라는 변수는 stack에 생성되는 건 같지만, "Hello"라는 값은 일반 Heap 메모리 내에 생성되게 된다. ⇒ new 연산자를 사용한 경우, 계속 새로운 인스턴스가 생성되게 된다.
  • String a = new String("Hello");
    String b = new String("Hello");
    boolean c = a==b;
    System.out.println(c);  //false, a와 b의 주소가 다름.

 

반응형

'JAVA' 카테고리의 다른 글

[JAVA]Object (equals, hashCode ...)  (0) 2022.02.08
[JAVA]JAVA Annotaion (+Lombok제공 Annotaion 정리)  (0) 2022.02.06
[JAVA]배열 (Array)  (0) 2021.02.04
Comments