Algorithm

[JAVA] Cache 그리고 Equals 헷갈리는 Integer와 int에 대하여

랩실외톨이 2024. 7. 10. 05:35
반응형

1. Cache

Java의 Integer 클래스는 Integer.valueOf(int i) 메서드를 사용할 때 특정 범위의 값을 캐싱합니다. 이 범위는 기본적으로 -128에서 127까지입니다. 이 범위 내의 값들은 새로운 객체를 생성하지 않고 미리 캐시된 객체를 반환합니다.

 

public class IntegerCacheExample {
    public static void main(String[] args) {
        Integer a = Integer.valueOf(127);
        Integer b = Integer.valueOf(127);

        Integer c = Integer.valueOf(128);
        Integer d = Integer.valueOf(128);

        System.out.println(a == b); // true, because they are cached and refer to the same object
        System.out.println(c == d); // false, because they are not cached and refer to different objects
    }
}

 

 

2. equals 메서드

Integer 클래스의 equals 메서드는 두 객체가 같은 값을 가지는지를 비교합니다. 기본 자료형 int는 == 연산자를 사용하여 값을 직접 비교합니다.

 

public class IntegerEqualsExample {
    public static void main(String[] args) {
        Integer a = new Integer(127);
        Integer b = new Integer(127);

        int x = 127;
        int y = 127;

        System.out.println(a.equals(b)); // true, because equals() compares values
        System.out.println(a == b); // false, because they are different objects
        System.out.println(x == y); // true, because they are primitive types and their values are compared
    }
}

 

 

여기서 내가 겪은 문제!

 

int는 그냥 '=='으로 비교 가능하고, 자료형이 바뀌었을 때만 equals를 쓴다고 착각했습니다.

int는 기본 자료형(primitive type)이고, Integer int의 래퍼 클래스(wrapper class)입니다.

 

즉, Integer cache로 인해서 -128에서 127 까지는 '=='으로 비교가 가능하지만 그 범위를 넘으면 객체이기 때문에 그 값이 같더라도 다른 객체라 equals로 비교해줘야 했던 것입니다...

 

하필 예제는 테케가 작아서 상관없었지만, -1414를 비교해야 하는 상황에서 찍어보니 그 값은 같은데 그냥 넘어가서 문제임을 또 깨달아버렸습니다...

 

알면서도 String 같은 자료형만 equals라고 착각했던 이 잘못된 개념을 언제쯤 맞게 기억할련지...잊지 않으려고 로그남김.

 

 

 

https://coding-log.tistory.com/259

 

[JAVA] 참조형 변수(Reference Type) 비교하기 ("==" vs equals())(Feat. Cache, Integer, Long)

자바에는 자료형이 기본형과 참조형으로 나눈다. 쉽게 말하자면 int는 기본형이고 Integer는 참조형이다. 둘은 똑같이 int범위 내의 정수를 담아내는 변수이다. 그러나 int는 그냥 우리가 아는 숫자

coding-log.tistory.com

 

 

사실 전에도 비슷한 글 남긴적 있음... 그냥 치매인듯.

 

 

 

 

반응형