우리가 어떤 변수나 함수의 자료형을 필요에 따라서 여러개로 바꿀 수 있다면 어떨까요? 어떤 특정한 값이 하나의 참조 자료형이 아니라 여러 개를 쓸 수 있도록 하는 것이 바로 Generic Programming입니다. 예를 들어서 요리를 하는데, 들어가는 재료가 다르다고 합시다. 닭고기 카레와 소고기 카레가 있는데, 들어가는 것이 닭이냐 소냐 이 차이만 있을 뿐, 하는 과정은 처음부터 끝까지 완벽하게 똑같습니다. 이런 경우에 레시피를 아예 각각 다르게 쓰는게 효율적일까요 아니면 재료 부분만 다르게 적는게 효율적일까요? 마찬가지로 제네릭 역시 자료형 매개변수 T를 통해서 여러 가지 자료형을 써먹을 수 있게 해줍니다.
public class Generic {
public static void main(String[] args) {
Box<Integer> box = new Box<Integer>(0); //wrapper클래스 사용해야함 그냥 int 안 됨!
System.out.println(box.getTemp() + 12);
Box<String> sbox = new Box<String>("hello");
System.out.println(sbox.getTemp() + " world");
}
}
class Box<T>{
T temp;
public Box(T temp) {
super();
this.temp = temp;
}
public T getTemp() {
return temp;
}
public void setTemp(T temp) {
this.temp = temp;
}
}
위의 예제를 보면, Box<Integer> box = new Box<Integer>(0); 이렇게 Box를 선언하여 생성하였습니다. 여기서 Box<Integer>는 제네릭 자료형(Generic type)이며, Integer는 대입된 자료형입니다. Generic으로 구현하면 형변환을 해주지 않아도 <T>의 자료형의 따라 컴파일하므로 코드를 더 간결하게 쓸 수 있다는 장점이 있습니다.
public class Generic {
public static void main(String[] args) {
BoxMap<Integer, String> cbox = new BoxMap<Integer, String>(0, null);
cbox.setKey(111);
cbox.setValue("hello");
System.out.println(cbox.getKey() + cbox.getValue());
}
}
class BoxMap<KEY, VALUE>{
KEY key;
VALUE value;
public BoxMap(KEY key, VALUE value) {
super();
this.key = key;
this.value = value;
}
public KEY getKey() {
return key;
}
public void setKey(KEY key) {
this.key = key;
}
public VALUE getValue() {
return value;
}
public void setValue(VALUE value) {
this.value = value;
}
}
자료형 매개변수를 2개 받을 수도 있는데요, 이 경우에는 각각 set, get을 해줘야 합니다. 초기화를 Integer는 0으로, String은 null로 한 상태에서
cbox.setKey(111); cbox.setValue("hello");를 하고 System.out.println(cbox.getKey() + cbox.getValue());을 출력해주면 111hello가 출력되게 됩니다.
'Java > 기초 Java' 카테고리의 다른 글
[기초 자바] List 인터페이스, ArrayList (0) | 2021.05.21 |
---|---|
[기초 자바] 상속의 기초 개념(1) (0) | 2021.05.18 |
[기초 자바] 피보나치 수열 (0) | 2021.05.13 |
[기초 자바] String class (0) | 2021.05.11 |
[기초 자바]wrapper class (0) | 2021.05.11 |