본문 바로가기
Language/java

[Java] 지네릭스_지네릭 메서드

by gamxong 2022. 7. 29.

지네릭 메서드

: 메서드의 선언부에 지네릭 타입이 선언된 메서드

: 지네릭 타입의 선언 위치는 반환 타입 바로 앞

static <T> void sort(List<T> list, Comparator<? super T> c)

★ 지네릭 클래스에 정의된 타입 매개변수와 지네릭 메서드에 정의된 타입 매개변수는 전혀 별개의 것.

 -  지네릭 메서드는 지네릭 클래스가 아닌 클래스에도 정의될 수 있음.

 -  static멤버에는 타입 매개변수를 사용할 수 없지만, 이처럼 메서드에 지네릭 타입을 선언하고 사용하는 것은 가능

 -  메서드에 선언된 지네릭 타입은 메서드 내에서만 지역적으로 사용될 것이므로 메서드가 static이건 아니건 상관 없음.

 

 

public static void printAll(ArrayList<? extends Product> list, ArrayList<? extends Product> list2) {
	for(Unit u : list) {
    	System.out.println(u);
    }
}

//same

public static <T extends Product> void printAll(ArrayList<T> list, ArrayList<T> list2) {
	for(Unit u : list) {
    	System.out.println(u);
    }
}

 

 

public static <T extends Comparable<? super T>> void sort(List<T> list)

1. 타입 T를 요소로 하는 List를 매개변수로 허용한다.

2. 'T'는 Comparable을 구현한 클래스이어야 하며 (<T extends Comparable>)

    ▷ Comparable 인터페이스여도 표기는 extends로 해서 T에서 구현해야 함,

   

  'T'또는 그 조상의 타입을 비교하는 Comparable이어야 한다는 것(Comparable<? super T>)을 의미한다. 

     

  만일 T가 Student이고, Person의 자손이라면, <? super T>는 Student, Person, Object가 모두 가능하다.

 

댓글