본문 바로가기

카테고리 없음

[JAVA] Pair 클래스

자바에서 Pair라이브러리가 없기 때문에 아래와 같이 만든다. 코드를 설명하면

T와 S는 제너릭이다. 만들고 싶은 짝으로 만들면 된다. Pair<Integer, Boolean>나 Pair<Integer, Integer>이 있다.

Pair생성자를 만드려면 제너릭과 같은 타입으로 만들면 된다.

    public Pair(T first, S second) {
      this.first = first;
      this.second = second;
    }
    
        Pair<Integer, Boolean> A = new Pair<Integer, Boolean>(1, false);

그런데 위와 같이 만들면 생성자를 만들 때마다 매번 일일이 Piar<Integer, Boolean>(1, false)로 지정해준다.

    //<T, S>는 return값이다. public int add()와 같은 의미이다.
    static <T,S> Pair<T,S> add(T first, S second){
        return new Pair<T,S>(first, second);
    }
}


    Pair.add(1,false);

그래서 조금 더 편리하게 만들기 위해서 Pair클래스 자체에 메소드를 만든다.

여기서 <T, S> Pair<T, S>는 public int add(){}와 같이 사용되는 제너릭 메소드의 반환타입이된다.

Student클래스가 이미 지정되어있다면, public Student add(){}로 쓸 수도 있다.

그런데 현재 제너릭 클래스가 생성될 때마다 <T, S>값이 저장되어있지 않으므로,

Pair<T, S>를 반환 리턴값으로 지정해줘야한다.

그런데 Pair<T,S>앞에 <T, S>가 또 붙은 이유는 메소드에 들어갈 타입을 지정해줘야 하기 때문이다.

class Person<T, S>{
    public T info;
    public S id;
    Person(T info, S id){ 
        this.info = info;
        this.id = id;
    }
    public <U> void printInfo(U info){
        System.out.println(info);
    }
}
//출처 : https://www.opentutorials.org/course/1223/6237

 

전체적인 코드는 아래와 같다.

class Pair<T,S> {
    T first;
    S second;

    public Pair(T first, S second) {
      this.first = first;
      this.second = second;
    }

    //<T, S>는 return값이다. public int add()와 같은 의미이다.
    static <T,S> Pair<T,S> add(T first, S second){
        return new Pair<T,S>(first, second);
    }
}


    Pair.add(1,false);