[JAVA/자바] Pair class만들어서 사용

2022. 2. 13. 15:50JAVA

Pair

  • 종종 자바로 bfs 문제를 풀 때, x좌표와 y좌표를 한 번에 que에 넣고 싶어 que를 <int, int>로 선언하지만 이렇게 할 경우 에러가 발생한다.
  • 2개의 값을 한 개의 que에 넣기 위해 C++에 있는 pair를 class로 만들어보자.

 

 

Pair Class

  public class Pair{
      int x,y;
      Pair(int x, int y){
          this.x=x;
          this.y=y;
      }
}
  • int가 아닌 pair 안에 들어갈 값이 string이면 int를 string으로 변경하면 된다.
  • 만약 상황에 따라 다른 자료형 타입이 들어가야 한다면 아래와 같이 Pair 클래스의 변수를 설정해주면 된다.
public class Pair<L,R>{
     L left;
     R right;
     Pair(L x, R y){
         this.left=x;
         this.right=y;
     }
}
  • L, R, left, right는 상황에 따라 다른 이름으로 사용해도 된다. (그냥 변수명이다.)

 

 

Pair Class Main에서 이용

  • Pair 안에 int가 들어갈 경우
import jdk.nashorn.internal.parser.JSONParser;
import java.util.LinkedList;
import java.util.Queue;

public class PairTest {
    public static void main(String[] args) {
        Queue<Pair> que=new LinkedList<>();
        que.add(new Pair(4,3)); // 넣기
        Pair test=que.poll(); // 꺼내기

        // 변수에 넣어서 출력
        int nx= test.x;
        int ny=test.y;
        System.out.println(nx+" "+ny);

        // 꺼내고 바로 출력
        System.out.println(test.x+" "+test.y);
    }

    public static class Pair{
        int x,y;
        Pair(int x, int y){
            this.x=x;
            this.y=y;
        }
    }
}
  • Pair 안에 들어갈 자료형이 유동적인 경우
import jdk.nashorn.internal.parser.JSONParser;
import java.util.LinkedList;
import java.util.Queue;

public class PairTest {
    public static void main(String[] args) {
        Queue<Pair> que=new LinkedList<>();
        que.add(new Pair("test",3)); // 넣기
        Pair test=que.poll(); // 꺼내기
        
        // 변수에 넣어서 출력
        String temp1= String.valueOf(test.left);
        int temp2=Integer.parseInt(String.valueOf(test.right));
        System.out.println(temp1+" "+temp2);
        
        // 꺼내고 바로 출력
        System.out.println(test.left+" "+test.right);
    }

    public static class Pair<L,R>{
        L left;
        R right;
        Pair(L x, R y){
            this.left=x;
            this.right=y;
        }
    }
}