Java - Generic
List list = new ArrayList(); list.add("hello"); String str = (String) List.get(0); List list = new ArrayList; list.add("hello"); String str = list.get(0);
public class 클래스명<T> public interface 인터페이스명<T> public class 클래스명<AnyThingVariableNaming> ----> 변수명 쓰듯 쓰는게 가능 public interface 인터페이스명<AnyThingVariableNaming> ----> 마찬가지E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th typespublic class Box<T> { private T t; public T get() { return t; } public void set(T t) { this.t = t; } }Box<String> box = new Box<String>; public class Box<String> { private String t; public String get() { return t; } public void set(String t) { this.t = t; } }
List<String> list; ----> 일반적인 제네릭타입 형식의 컬렉션 List list2 ----> Raw Typepublic class RawType<T> { public List<String> getStrs() { return Arrays.asList("str"); } public static void main(String[] args) { RawType t = new RawType(); ---->> Raw Type for (String str : t.getStrs()) { ---->> compile error System.out.println(str); } } }
public <타입파라미터,...> 리턴타입 메소드명(매개변수,...) {...} public <T> Box<T> boxing(T t) {...}리턴타입 변수 = <구체적인 타입> 메소드명(매개값); 리턴타입 변수 = 메소드명(매개값); Box<Integer> box = <Integer>boxing(100); Box<Integer> box = boxing(100);
public <T extends Number> int compare(T t1, T t2) {...}
public class Product<T> {...} public class ChildProduct<T,M> extends Project<T> {...} public class EtcProduct<T,M,C> extends ChildProduct<T,M> {...}

Last updated