Java Generic - 기본기 다지기

  • 다음 코드의 실행 결과를 참고해 Container 클래스를 만들기
  • Container 클래스는 제네릭이다.

Main.class

public class Main {
    public static void main(String[] args) {
        Container<String> string = new Container<>();
        System.out.println("빈값 확인하기 = " + string.isEmpty());

        string.setItem("collection");
        System.out.println("저장한 데이터 = " + string.getItem());
        System.out.println("빈값 확인하기 = " + string.isEmpty());

        Container<Integer> int = new Container<>();
        int.setItem(10);
        System.out.println("저장한 데이터 = " + int.getItem());
    }
}

빈값 확인하기 = true
저장한 데이터 = collection
빈값 확인하기 = false
저장한 데이터 = 10


풀이

Container.class

public class Container<T> {
    private T value;

    boolean isEmpty() {
        return value == null;
    }

    void setItem(T value) {
        this.value = value;
    }

    public T getItem() {
        return value;
    }
}


두번째 문제 - Pair 클래스 만들기

  • Pair 클래스는 제네릭 클래스이다.
  • 다음 코드 실행 결과를 살펴보고 Pair 클래스를 작성한다.

Main.class

public class Main {
    public static void main(String[] args) {
        Pair<Integer, String> pair1 = new Pair<>();
        pair1.setFirst(10);
        pair1.setSecond("data");
        System.out.println(pair1.getFirst());
        System.out.println(pair1.getSecond());
        System.out.println("pair = " + pair1);

        Pair<String, String> pair2 = new Pair<>();
        pair2.setFirst("key");
        pair2.setSecond("value");
        System.out.println(pair2.getFirst());
        System.out.println(pair2.getSecond());
        System.out.println("pair = " + pair2);
    }
}

10
data
pair = Pair{key=10, value=data}
key
value
pair = Pair{key=key, value=value}

Pair.class

public class Pair<K, V> {
    private K key;
    private V value;

    void setFirst(K key) {
        this.key = key;
    }

    void setSecond(V value) {
        this.value = value;
    }

    public K getFirst() {
        return key;
    }

    public V getSecond() {
        return value;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "key=" + key +
                ", value=" + value +
                '}';
    }
}