본문 바로가기
공부/이펙티브자바

[이펙티브자바]item 26.로 타입은 사용하지 말라

by 띵커베르 2023. 2. 10.
728x90
  • 로(raw)타입을 사용하면 런타임에 예외가 일어날 수 있으니 사용하면 안 된다.
  • 로 타입은 제네릭이 도입되기 이전 코드와의 호환성을 위해 제공될 뿐이다.

 

  • 로 타입이란 제네릭 타입에서 타입 매개변수를 전혀 사용하지 않을 때를 말한다 ex)List, Set
  • 로 타입을 쓰면 제네릭이 안겨주는 안정성과 표현력을 모두 잃게 된다.
    • 애초에 왜 만들어놓은 걸까?: 이전 버전의 코드들의 호환성 때문이다.
  • 비한정적 와일드카드 타입: <?> => 타입이 안전하다.
  • 아래는 로타입으로 일어날 수 있는 안정성 예제이다.
public class Numbers {
    static int numElementsInCommon(Set<?> s1, Set<?> s2) {
    //한정적 와일드카드 타입으로 인한 add 불가능.
    //s1.add(**)
        int result = 0;
        for (Object o1 : s1) {
            if (s2.contains(o1)) {
                result++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        System.out.println(Numbers.numElementsInCommon(Set.of(1, 2, 3, 4), Set.of(1, 3)));
    }
}​
public class Raw {
    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        unsafeAdd(strings, Integer.valueOf(42));
        String s = strings.get(0); // 해당 부분에서 exception 발생.
    }
	//object 매개변수를 받아 add 하기때문에 컴파일이 잡아내질 못함.
    private static void unsafeAdd(List list, Object o) {
        list.add(o);
    }
}

 

728x90

댓글