코테 공부

Comparable, Comparator [인터페이스]

DaEun_ 2023. 2. 10. 15:50

정렬

1) comparable하게 만들거나

2) Comparator를 주던가 

 

Comparable

원소 스스로가 타 원소와 비교가능하게 만들고 싶을 때 

 

int CompareTo( E e ) 

1. 음수: 상대가 크다 -> 그대로

2. 자연수: 내가 크다 -> 교환 

3. 0: 둘이 같다. 

 

Student[] st= {
				new Student(1,89),
				new Student(10,78),
				new Student(5,100)
		};
		
System.out.println("정렬 전: "+Arrays.toString(st));
Arrays.sort(st);//Comparable한 타입이 아니기 때문에 에러남
System.out.println("정렬 후: "+Arrays.toString(st));

Comparable한 타입이 아니기 때문에 다음 정렬 식은 에러가 난다. 

 

 

따라서 Student 클래스에 Comparable하게 해주어 정렬이 되게 한다. 

public class Student implements Comparable<Student>{
	int no, score;

	public Student(int no, int score) {
		super();
		this.no = no;
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [no=" + no + ", score=" + score + "]";
	}

	@Override
	public int compareTo(Student o) {
    
    	//1. this객체가 작으면 -1, 같으면 0, 크면 1 리턴한다. 
		return this.no<o.no? -1: this.no==o.no?0:1;
		
        //2.
        return this.no-o.no;//오름차순 
		
        //3. 
        return Integer.compare(this.no, o.no);
	}
    
  }

 

** 수행 결과(정상적)

 

 

 

Comparator

원소와 상관 없는 제 3의 대상으로 두 원소를 받아 비교 판단해주는 도우미 

 

 

int Compare(E e1, E e2 ) 

 

 

1. Student 클래스 객체 정렬하기 

Arrays.sort(st, new Comparator<>() {

			@Override
			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return o1.no-o2.no;
			}
			
		});

 

 

 

** 수행 결과 

no 값을 기준으로 오름차순으로 정렬

 

 

 

Arrays.sort(st, Comparator.reverseOrder());

 

 

** 실행 결과 

no 기준으로 내림차순으로 정렬

 

 

 

2. int 배열 값 정렬하기 

 int[] arr3= {4,3,7,9,10}; //comparable 하지 않아서 정렬되지 않음 

Integer[] arr3= {4,3,7,9,10}; //Integer 타입으로 변경하여 정렬
Arrays.sort(arr3, Comparator.reverseOrder());

 

 

3. 2차원 배열 정렬

		System.out.println("정렬 전: "+Arrays.deepToString(arr));
		Arrays.sort(arr);
		System.out.println("정렬 후: "+Arrays.deepToString(arr));

위의 식은 에러가 난다. 

따라서 Comparator를 주어 에러를 해결한다. 

 

		System.out.println("정렬 전: "+Arrays.deepToString(arr));
		Arrays.sort(arr, (a, b)->a[0]-b[0]);
		
		System.out.println("정렬 후: "+Arrays.deepToString(arr));

 

-- > 위의 식은 원소의 첫번째 값으로 비교, 오름차순으로 정렬한다. 

 

 

 

람다식 정렬

 

		Arrays.sort(st, (o1,o2)->-1*Integer.compare(o1.score, o2.score));
		System.out.println("정렬 후: "+Arrays.toString(st));
		Arrays.sort(st, (o1,o2)->Integer.compare(o1.score, o2.score));
		System.out.println("정렬 후: "+Arrays.toString(st));

 

** 실행 결과 

score를 기준으로 내림차순, 오름차순으로 정렬