좌충우돌 개발

Generic

|

Generic

사용의 장점

  1. Compile 시점에 type 체크가 가능하다
  2. 중복 코드 제거

Raw Type : Generic을 사용하면서 parameter Type을 지정하지 않는 경우

List list = new ArrayList<Integer>();

Compile 시점에 raw type을 허용하는 이유는 이전 java의 호환성을 위해서이다.

Generic method

<T> void printExample(T t) { system.out.println(t.toString);}

Class level 의 type parameter는 instance가 생성될때 값을 받아온다.
그러므로 static method에서는 해당 type parameter를 사용할 수 없다.
Static method에서는 를 사용할 때는 method level에서 parameter type을 선언해서 사용해야 한다.

Bounded type parameter : type parameter에 제한을 둔다
Multiple bound : 여러 type parameter 제약을 줄 수 있다. Interface 는 여러가지고 올 수 있으나 class는 하나만 올 수 있다.

class ExampleClass <T extends List> {
 // bounded type parameter
}

Comparable interface : 객체간의 크기를 비교 하기 위해서 compareTo() 구현

Type hint : method 앞에 해당 타입을 명시하여 컴파일러가 추론하지 않고 바로 알도록 만든다. Java 하위 버전에 타입 추론을 하지 못할 때 사용한다.

List<String> list = Collection.<String>emptyList();

<?> 와일드 카드의 유용성과 제한성
와일드 카드의 의미는 ‘모른다’ 이다. 그러므로 기본적인 와일드 카드가 사용은 기본적인 것만 method 내부에서 사용할 때 사용되어진다.
예를 들어 List<?> 의 경우 method 내부에서 List의 기본 기능만 사용한다는 뜻이다.
비교하여 List 는 method 내부에서 T type의 기능을 사용한 다는 뜻이다.

JAVA spec method 안에서 사용되어 질 때는에 extends T method 외부에서 사용되어 질 때에는 super T

public static long frequency(List<?> list, Object elem) {
        return list.stream().filter(s->s.equals(elem)).count();    
}

Capture : type 추론 Capture Error: type 추론이 불가능할 경우 발생 Capture helper 함수를 만든다. ( 단점: 함수 호출에 대한 부하가 발생할 수 있다.)

IntersectionType @FuntionalInterface

Marker interface : method를 하나도 가지지 않는 interface 예: serializable

Default method: interface 안에 method를 구현 할수 있게 한것

Comments