JAVA

JAVA 제네릭

테라시아 2024. 11. 17. 14:34

Generic
    - 데이터의 타입을 일반화한다(Generalize)
    - 클래스와 메서드에서 사용할 타입을 설계도에 저장하지 않고
      컴파일할 때 지정하는 기술
      -> 사용자가 사용할 때 타입을 결정
    - JDK 1.5 때 도입, 그 전에는 Object를 사용
    - Object를 사용하면
      데이터 입력 시 모든 데이터 입력이 가능하므로
      잘못된 데이터가 들어갈 수 있으며
      데이터 사용 시에도 데이터 타입을 모르니
      알게 되더라도 Casting을 반드시 해야 사용 가능

    Animal<T> : T, K, V, E

 

☆ Code

 

★ Generic1

import java.util.ArrayList;

public class Generic1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Food ramen = new Food("라면", "그냥 끓이면 됨 아님 날로 먹음");
		
		// OldBox
		OldBox ob = new OldBox();
		ob.add(ramen);
		System.out.println(((Food)(ob.get(0))).getRecipe());
		
		// NewBox
		NewBox<Food> nb = new NewBox();
		nb.add(ramen);
		System.out.println(nb.get(0).getRecipe());
	}

}

class Food {
	String name;
	String recipe;
	
	Food(String name, String recipe){
		this.name = name;
		this.recipe = recipe;
	}
	
	String getRecipe() {
		return recipe;
	}
}

class OldBox {
	ArrayList item = new ArrayList();
	
	void add(Object o) {
		item.add(o);
	}
	
	Object get(int index) {
		return item.get(index);
	}
}

class NewBox<T> {
	ArrayList<T> item = new ArrayList();
	
	void add(T o) {
		item.add(o);
	}
	
	T get(int index) {
		return item.get(index);
	}
}

class StrangeBox<DisneyLand> {
	DisneyLand name;
}

 

★ Generic2

import java.util.ArrayList;

public class Generic2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LuxuryBox<Instrument> box1 = new LuxuryBox();
		LuxuryBox<Violin> box2 = new LuxuryBox();
		LuxuryBox<Flute> box3 = new LuxuryBox();
		
		Bat bat1 = new Bat();
		System.out.println(box3.<String>get("Cello"));
		System.out.println(box3.<Bat>get(bat1));		
	}

}

class Instrument {   }
class Violin extends Instrument {   }
class Flute extends Instrument {   }

class SportsTool {   }
class Bat extends SportsTool {   }

class LuxuryBox<T extends Instrument> {
	ArrayList<T> item = new ArrayList();
	
	public <T> T get(T data) {
		return data;
	}
}