: 타입을 컴파일 시점에서 미리 정하는 것
class DDBoxDemo {
public static void main(String[] args) {
DBox<String, Integer> box1 = new DBox<>();
box1.set("Apple", 25);
DBox<String, Integer> box2 = new DBox<>();
box2.set("Orange", 33);
DDBox<DBox<String, Integer>, DBox<String, Integer>> ddbox = new DDBox<>();
ddbox.set(box1, box2);
System.out.println(ddbox);
}
}
/*
==================
Apple & 25
Orange & 33
*/
class DBox<L, R> {
private L left; // 왼쪽 수납 공간
private R right; // 오른쪽 수납 공간
public void set(L o, R r) {
left = o;
right = r;
}
@Override
public String toString() {
return left + " & " + right;
}
}
// 제네릭 = 타입을 컴파일 시점에서 미리 정하는 것
public class Java_01 {
DBox<String, Integer> box = new DBox<String, Integer>();
box.set("Apple", 25);
System.out.println(box);
box.set("Orange", 33);
System.out.println(box);
}
}
public static void main(String[] args) {
Box<Integer> box1 = new Box<>();
box1.set(99);
Box<Integer> box2 = new Box<>();
box2.set(55);
System.out.println(box1.get() + " & " + box2.get());
swapBox(box1, box2);
System.out.println(box1.get() + " & " + box2.get());
}
/*
==========
99 & 55
55 & 99
*/
public class Box<T> {
private T ob;
public void set(T o) {
ob = o;
}
public T get() {
return ob;
}
}
public class Java_04 {
public static void main(String[] args) {
Box<Integer> box1 = new Box<>();
box1.set(99); // 오토 박싱
Box<Integer> box2 = new Box<>();
box2.set(55); // 오토 박싱
System.out.println(box1.get() + " & " + box2.get());
swapBox(box1, box2);
System.out.println(box1.get() + " & " + box2.get());
}
public static <T> void swapBox(Box<T> box1, Box<T> box2) {
T temp = box1.get();
box1.set(box2.get());
box2.set(temp);
}
}
: 메소드 선언 시에 매개변수나 반환 타입에 타입 매개변수를 사용하여 일반화된 타입을 처리하는 메소드
public <T> 반환타입 메소드명(매개변수들) {// 메소드 구현}
ArrayList
LinkedList
• 인스턴스의 저장 순서 유지
• 동일 인스턴스의 중복 저장을 허용한다.