Objects.compare(T a, T b, Comparator<T>c) 메소드 : 두 객체를 비교자(Comparator=c)로 비교해서 int 값 리턴

implements Comparator<T> 필수

 

T = 비교할 객체 타입

 

a > b 일 때, 양수 리턴

a = b 일 때, 0 리턴

a < b 일 떄, 음수 리턴

package sec04.exam01_objects_YJ;

import java.util.Comparator;
import java.util.Objects;

public class CompareExample {
	static class Student {
		int sno;
		Student(int sno) {
			this.sno = sno;
		}
	}
	
	static class StudentComparator implements Comparator<Student> {

		@Override
		public int compare(Student a, Student b) {
			return Integer.compare(a.sno, b.sno); //아래와 같은 의미
			/*if(a.sno < b.sno) return -1;
			//else if(a.sno == b.sno) return 0;
			else return 1;*/
		}
	}
	
	public static void main(String[] args) {
		Student s1 = new Student(1); //학번이 1인 학생 객체 생성
		Student s2 = new Student(1); //학번이 1인 학생 객체 생성
		Student s3 = new Student(10); //학번이 1인 학생 객체 생성
		
		int result = Objects.compare(s1, s2, new StudentComparator());
		System.out.println("s1, s2 compare result: " + result);
		
		result = Objects.compare(s1, s3, new StudentComparator());
		System.out.println("s1, s3 compare result: " + result);
		
		
		
	}
}
s1, s2 compare result: 0
s1, s3 compare result: -1

+ Recent posts