제네릭(Generic)이란?
제네릭을 사용함으로서 얻는 이점
List list = new ArrayList(); list.add("hello"); -> String str = (String)list.get(0) |
List<String> list = new ArrayList<String>(); list.add("hello"); String str = list.get(0); |
제네릭 타입이란
타입을 파라미터로 가지는 클래스와 인터페이스를 말한다.
타입 파라미터
제네릭 타입을 사용할 경우의 효과
public class testBox {
private Object object;
public Object getObject() { return object; }
public void setObject(Object object) { this.object = object; }
public static void main(String[] args) {
testBox box = new testBox();
box.setObject("hello"); //String 타입을 Object 타입으로 자동 타입 변환 후 저장
String str = (String) box.getObject();//Object 타입을 String 타입으로 강제 타입 변환 후 얻음
}
}
제네릭 적용 불필요한 타입변환이 필요 없어짐. 제네릭 타입을 사용할때( 제네릭타입의 객체를 만들때 ?) T 부분을 원하는 타입을 주면 된다.
public class TestGenericBox<T> {
private T t;
public T getT() { return t; }
public void setT(T t) { this.t = t; }
public static void main(String[] args) {
TestGenericBox<String> stringGecericBox = new TestGenericBox<String>();
stringGecericBox.setT("hello");
String str = stringGecericBox.getT();
}
}
두 개 이상의 타입 파라미터를 사용해서 선언할 수 있다.
public class 두개이상의타입파라미터<T, M> {
private T kind;
private M model;
public T getKind() { return kind; }
public void setKind(T kind) { this.kind = kind; }
public M getModel() { return model; }
public void setModel(M model) { this.model = model; }}
중복된 타입 파라미터를 생략한 다이아몬드( <>) 연산자
두개이상의타입파라미터<Tv, String> 티비 = new 두개이상의타입파라미터<Tv, String>();
//다이아몬드연산자 적용
두개이상의타입파라미터<Tv, String> 티비 = new 두개이상의타입파라미터<>();
Exam
public static void main(String[] args) {
// 제네릭 을 사용사여 생성시 Tv 타입과 String 타입을 지정후 set, get 실행
두개이상의타입파라미터<Tv, String> product1 = new 두개이상의타입파라미터<>();
produck1.setKind(new Tv());
product1.setModel("스마트 TV");
Tv tv = product1.getKind();
String tvModel = product1.getModel();
// 제네릭 을 사용사여 생성시 Car 타입과 String 타입을 지정후 set, get 실행
두개이상의타입파라미터<Car, String> product2 = new 두개이상의타입파라미터<>();
product2.setKind(new Car());
product2.setModel("리어카");
Car car = product2.getKind();
String carModel = product2.getModel();
'JAVA > JAVA' 카테고리의 다른 글
제네릭(Generic) 타입의 상속과 구현 (0) | 2018.06.09 |
---|---|
제네릭(Generic) 와일드카드 타입 (0) | 2018.06.09 |
제네릭(Generic) 메소드 (0) | 2018.06.08 |
Thread 정리..?? (0) | 2018.06.08 |
자바 기본 변수 (0) | 2018.05.08 |