E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
알수없는 타입 -> ?
public class Test<K, V> implements Pair<K, V> {
private K key;
private V value;
public Test(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
// TODO Auto-generated method stub
return key;
}
@Override
public V getValue() {
// TODO Auto-generated method stub
return value;
}
}
interface Pair<K, V> {
public K getKey();
public V getValue();
}
====================================
public class Test {
public static void main(String args[]) {
Box box = new Box();
box.set("sdf");
System.out.println(box.get());
}
}
class Box {
private Object object;
public void set(Object object) { this.object = object; }
public Object get() { return object; }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
public class Test {
public static void main(String args[]) {
Box<String> box = new Box<String>("abc");
System.out.println(box.get());
}
}
class Box<T> {
private T t;
public Box(T t) {
super();
this.t = t;
}
public void set(T t) { this.t = t; }
public T get() { return t; }
}
----------------------------------------------------------------------------------
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public <U extends Number> void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.set(new Integer(10));
integerBox.inspect("some text"); // error: this is still String!
}
}
=-----------------------------------------------------------------------------
class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) { this.n = n; }
public boolean isEven() {
return n.intValue() % 2 == 0;
}
}
public class Test {
static String[] oa = new String[100];
static Collection<Object> co = new ArrayList<Object>();
public static void main(String[] args) {
fromArrayToCollection(oa, co);
}
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // Correct
}
System.out.println(c);
}
}
-----------------------------------------------------
interface Type<T> {
T doSomething(T name);
}
public class GenericTest<T> implements Type<T> {
public static void main(String[] args) {
GenericTest<String> g = new GenericTest<>();
System.out.println(g.doSomething("asd"));
GenericTest<Integer> g2 = new GenericTest<>();
System.out.println(g2.doSomething(123));
}
@Override
public T doSomething(T name) {
return name;
}
}
result :
asd
123