Skip to content

Instantly share code, notes, and snippets.

ObjectBox objectBox1 = new ObjectBox();
objectBox1.store(new Melon()); // 컴파일통과
ObjectBox objectBox2 = new ObjectBox():
objectBox2.store(new Apple()); // 컴파일통과
Apple apple = (Apple)objectBox2.getItem(); // 컴파일통과
Melon melon = (Melon)objectBox2.getItem(); // 컴파일통과 런타임오류
AppleBox appleBox = new AppleBox();
appleBox.store(new Melon()); // 컴파일오류발생
MelonBox melonBox = new MelonBox():
melonBox.store(new Apple()); // 컴파일오류발생
class ObjectBox {
Object item;
public void store(Object item) {
this.item = item;
}
public Object getItem() {
return item;
class AppleBox {
Apple item;
public void store(Apple item) {
this.item = item;
}
public Apple getItem() {
return item;
List<String> strs = Arrays.asList("a", "b", "c", "d");
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6);
int size1 = GenericMethod.getListSize(strs);
int size2 = GenericMethod.getListSize(ints);
// Comparable 인터페이스를 구현해 봤다면 알 것이다.
// public interface Comparable<T> {
// public int compareTo(T o);
// }
class GenericInterfaceImpl implements Generic<String, Integer> {
@Override
public String doSomething(Integer t) {
return t.toString();
}
Generics<String> genercis = new Generics<>();
generics.set("Hello");
// list 사용할 때와 비교해보자. 똑같지 않나?
List<String> strs = new ArrayList<>();
class GenericMethod {
public static <T> int getListSize(List<T> list) {
int count = 0;
for (T t : list) {
count++;
}
return count;
}
}
interface Generic<T1, T2> {
T1 doSomething(T2 t);
T2 doSomething2(T1 t);
}
@ohjongsung
ohjongsung / GenericClass.java
Last active March 27, 2018 04:38
blog code snippets
public class Generics<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}