Java 지네릭 타입의 형변환
by 볼빵빵오춘기지네릭 타입의 형변환
- 지네릭 타입과 원시 타입 간의 형변환은 바람직 하지 않다.(경고 발생)
더보기



import java.util.*; class Fruit implements Eatable { public String toString() { return "Fruit";} } class Apple extends Fruit { public String toString() { return "Apple";}} class Grape extends Fruit { public String toString() { return "Grape";}} class Toy { public String toString() { return "Toy" ;}} interface Eatable {} public class Try { public static void main(String[] args) { Box b = null; Box<String> bStr = null; b = (Box)bStr; // 가능은 하지만 경고 Box<String> -> Box bStr = (Box<String>)b; // 가능은 하지만 경고 Box -> Box<String> } } class FruitBox<T extends Fruit & Eatable> extends Box<T> {} class Box<T> { ArrayList<T> list = new ArrayList<T>(); void add(T item) { list.add(item); } T get(int i) { return list.get(i); } int size() { return list.size(); } public String toString() { return list.toString();} }

- 와일드 카드가 사용된 지네릭 타입으로는 형변환 가능하다.
더보기



⇒ 2번째줄과 3번째 줄 동일하고
⇒ 3번째줄은 2번째줄에서 생략가능해서 생략해놓은 것이다.

import java.util.*; class Fruit implements Eatable { public String toString() { return "Fruit";} } class Apple extends Fruit { public String toString() { return "Apple";}} class Grape extends Fruit { public String toString() { return "Grape";}} class Toy { public String toString() { return "Toy" ;}} interface Eatable {} public class Try { public static void main(String[] args) { FruitBox<? extends Fruit> fbox = (FruitBox<? extends Fruit>)new FruitBox<Fruit>(); // 위 생성자 부분에 괄호부분 (FruitBox<? extends Fruit>) 은 생략가능 하다. // 원래는 들어가야한다. 아래코드는 생략된 코드이다. // FruitBox<Apple> -> FruitBox<? extends Fruit> FruitBox<? extends Apple> abox = new FruitBox<Apple>(); // FruitBox<? extends Fruit> -> FruitBox<Apple> 가능 ? FruitBox<Apple> appleBox = (FruitBox<Apple>)abox; // 가능. but 경고발생 // why? 오른쪽부분은 와일드카드로 선언되어있는데 왼쪽에 명확한 타입으로 바꿀려고 하니 // 경고가 발생하는 것 } } class FruitBox<T extends Fruit & Eatable> extends Box<T> {} class Box<T> { ArrayList<T> list = new ArrayList<T>(); void add(T item) { list.add(item); } T get(int i) { return list.get(i); } int size() { return list.size(); } public String toString() { return list.toString();} }
지네릭 타입의 제거
컴파일러는 지네릭 타입을 제거하고, 필요한 곳에 형변환을 넣는다.

⇒ why? 하위 호환성때문에



블로그의 정보
Hello 춘기's world
볼빵빵오춘기