[Java] Comparable & Comparator

진예·2024년 1월 3일
0

JAVA

목록 보기
6/10
post-thumbnail

💡 Comparable & Comparator

객체비교하는 인터페이스 ➡️ 구현해서 사용!


📒 Comparable

compareTo(Object o) : compareTo() 메서드를 호출한 객체(자기 자신)와 매개변수 객체 비교

ex) Comparable구현클래스 Student

  • compareTo(o)

    • 매개변수 객체의 값보다 경우 : 양수 반환
    • 매개변수 객체의 값과 같은 경우 : 0 반환
    • 매개변수 객체의 값보다 작은 경우 : 음수 반환
class Student implements Comparable<Student> {
	
	int age;
	int classNumber;
	

	public Student(int age, int classNumber) {
		super();
		this.age = age;
		this.classNumber = classNumber;
	}

	// comparable 구현
	@Override
	public int compareTo(Student o) {
		
        /*
		if(this.age > o.age) {
			return 1;
		}
		
		else if(this.age == o.age) {
			return 0;
		}
	
		else return -1;
	}
	*/
    
    return this.age - o.age;
}
  • s1.compareTo(s2) : 자기 자신의 나이 s1.age매개변수로 주어진 객체의 나이 s2.age를 비교했을 때, s2.age의 값이 더 크므로 음수를 반환 ➡️ s2의 나이가 더 많습니다! 출력
public class Test {
	public static void main(String[] args) {
		
		Student s1 = new Student(15, 1);
		Student s2 = new Student(17, 2);
		
		// 비교 결과값 저장
		int compare = s1.compareTo(s2);
		
		if(compare > 0) System.out.println("s1의 나이가 더 많습니다!");
		else if(compare < 0) System.out.println("s2의 나이가 더 많습니다!");
		else System.out.println("두 학생의 나이가 같습니다!");
	}
}


📒 Comparator

compare(Object o1, Object o2) : 두 매개변수 객체를 비교

ex) Comparator구현클래스 Student

  • compareTo(o1, o2)

    • o1 객체의 값이 큰 경우 : 양수 반환
    • 두 객체의 값이 같은 경우 : 0 반환
    • o1 객체의 값이 작은 경우 : 음수 반환
class Student implements Comparator<Student> {
	
	int age;
	int classNumber;
	

	public Student(int age, int classNumber) {
		super();
		this.age = age;
		this.classNumber = classNumber;
	}

	// Comparator 구현
	@Override
	public int compare(Student o1, Student o2) {
		return o1.age - o2.age;
	}
}
  • s1.compare(s2, s3) : 메서드를 호출한 s1과 상관없이, 매개변수로 주어진 s2s3 객체의 age비교 ➡️ s3.age가 더 크므로 음수 반환 ➡️ s3의 나이가 더 많습니다! 출력
public class Test {
	public static void main(String[] args) {
		
		Student s1 = new Student(15, 1);
		Student s2 = new Student(17, 2);
		Student s3 = new Student(18, 3);
		
		// 비교 결과값 저장
		int result = s1.compare(s2, s3);
		
		if(result > 0) System.out.println("s2의 나이가 더 많습니다!");
		else if(result < 0) System.out.println("s3의 나이가 더 많습니다!");
		else System.out.println("두 학생의 나이가 같습니다!");
	}
}

📝 익명 객체 활용

클래스 자체에서 인터페이스를 구현하는 것이 아닌, 필요한 경우익명 객체를 생성하여 사용!

  • 익명 객체여러 개 생성할 수 있으므로, 나이를 비교하는 compAge학번을 비교하는 compClass를 각각 구현하여 사용할 수 있다!
public class Test {
	
	public static void main(String[] args) {
		
		Student s1 = new Student(15, 1);
		Student s2 = new Student(17, 2);
		Student s3 = new Student(18, 3);
		
		// 익명 객체 : 나이 비교
		Comparator<Student> compAge = new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				return o1.age - o2.age;
			}
		};
		
		// 익명 객체 : 학번 비교
		Comparator<Student> compClass = new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				return o1.classNumber - o2.classNumber;
			}
		};
		
		// 비교 결과값 저장
		int resultAge = compAge.compare(s2, s3);
		
		if(resultAge > 0) System.out.println("s2의 나이가 더 많습니다!");
		else if(resultAge < 0) System.out.println("s3의 나이가 더 많습니다!");
		else System.out.println("두 학생의 나이가 같습니다!");
		
		// 비교 결과값 저장
		int resultClass = compClass.compare(s2, s3);
		
		if(resultClass > 0) System.out.println("s2의 학번이 더 큽니다!");
		else if(resultClass < 0) System.out.println("s3의 학번이 더 큽니다!");
		else System.out.println("두 학생의 학번이 같습니다!");
	}
}

class Student {
	int age;
	int classNumber;

	public Student(int age, int classNumber) {
		super();
		this.age = age;
		this.classNumber = classNumber;
	}
}


📒 정렬

Arrays.sort()Collections.sort()는 기본적으로 오름차순 정렬을 수행하는데, Comparator 구현 객체파라미터로 함께 넘기면 사용자가 정한 기준으로 정렬을 수행한다!

  • Integer[] 선언 : Comparator의 경우 참조형 타입만 사용 가능
Integer[] arr = {9, 4, 2, 7, 8};
  • Arrays.sort(int[]) : 오름차순 정렬
Arrays.sort(arr);
System.out.println("오름차순 : " + Arrays.toString(arr));

  • Arrays.sort(int[], Comparator<Integer>) : 내림차순 정렬
Arrays.sort(arr, new Comparator<Integer>() {

	@Override
	public int compare(Integer o1, Integer o2) {
		return o2.compareTo(o1);
	}
    
});
		
System.out.println("내림차순 : " + Arrays.toString(arr));

람다식으로 간단하게 표현 가능!

Arrays.sort(arr, (o1, o2) -> o2.compareTo(o1));

➕ 일반적으로 오름차순 정렬일 때는 o1 - o2, 내림차순 정렬일 때는 o2 - o1 순서로 사용한다.


🙇🏻‍♀️ 참고 : 자바 [JAVA] - Comparable 과 Comparator의 이해

profile
백엔드 개발자👩🏻‍💻가 되고 싶다

0개의 댓글