제네릭스(Generics)

  • 컴파일시 타입을 체크해 주는 기능
  • 객체의 타입 안정성을 높이고 형변환의 번거로움을 줄여줌
    • 하나의 컬렉션에는 대부분 한 종류의 객체만 저장
  • 장점
    • 타입 안정성을 제공
    • 타입체크와 형변환을 생략할 수 있으므로 코드가 간결해 진다.
import java.util.ArrayList;

class Fruit				  { 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";}}

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();}
}

public class FruitBoxEx {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Box<Fruit> fruitBox = new Box<Fruit>();
		Box<Apple> appleBox = new Box<Apple>();
		Box<Toy> toyBox = new Box<Toy>();
//		Box<Grape> grapeBox = new Box<Apple>(); // 에러. 타입 불일치		
		fruitBox.add(new Fruit());
		fruitBox.add(new Apple());


		appleBox.add(new Apple());
		appleBox.add(new Apple());
//		fruitBox.add(new Toy()); // 에러. Box<Apple>에는 Apple만 담을 수 있음

		toyBox.add(new Toy());
//		toytBox.add(new Apple()); // 에러. Box<Toy>에는 Toy만 담을 수 있음

		System.out.println(fruitBox);
		System.out.println(appleBox);
		System.out.println(toyBox);
	}
}