study

제네릭(Generics)

1. 타입 파라미터

class Box<T> {
    private T value;
    public void set(T value) {
        this.value = value;
    }
    public T get(){
        return value;
    }
}

public class GenericTest {
    public static void main(String... strings){

        // 타입 파라미터
        Box<String> box = new Box();
        box.set("Hello");
        String str = box.get();
        System.out.println(str); // Hello
    }
}

2. 제네릭 메서드

public class GenericTest2 {

    public static <T> T echo(T input) {
        return input;
    }
    
    public static void main(String... strings){

        // 제네릭 메소드
        String str2 = echo("hello");
        int i = echo(0);
        System.out.println(str2); // hello
        System.out.println(i); // 0
    }
}

3. 제네릭 인터페이스

// 제네릭 인터페이스
interface Transformer<T, R> {
    R transform(T input);
}

public class GenericTest3 implements Transformer<String, Integer> {

    public Integer transform(String input) {
        return input.length();
    }

    public static void main(String... strings){
        Integer length = new GenericTest3().transform("hello");
        System.out.println(length); // 5
    }
}

4. 와일드카드(?)

import java.util.ArrayList;
import java.util.List;

public class GenericTest4 {

    public static void main(String... strings){
        // 와일드카드(?)
        // <?>:어떤 타입이든 허용
        // <? extends T>:T 또는 T의 하위타입
        // <? super T>:T 또는 T의 상위타입
        List<?> list = new ArrayList<String>();
        List<? extends Number> list2 = new ArrayList<Integer>();
        List<? super Integer> list3 = new ArrayList<Number>();        
    }
}