일반적인 Arrys.sort()를 사용하면, 컴퓨터는 배열에 대해 정렬을 수행한다. 이는 컴퓨터의 내부적인 정렬이 아닌 각 자료형의 래퍼 클래스(Integer, String... etc)들이 Comparable 인터페이스를 구현함으로서 정렬이 가능한 것이다. 정렬 기준을 만드는데 있는 인터페이스에는 Comparable뿐만아니라 Comparator도 있다. 두 인터페이스 모두 객체를 비교한다는 같은 기능을 목적으로 고안된 것이다. 이 두 인터페이스는 Java Collection Framework에 소속되어있다.
Comparator Document : https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html
Comparator (Java SE 17 & JDK 17)
Type Parameters: T - the type of objects that may be compared by this comparator All Known Implementing Classes: Collator, RuleBasedCollator Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambd
docs.oracle.com
Comparable Document : https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Comparable.html
Comparable (Java SE 17 & JDK 17)
Type Parameters: T - the type of objects that this object may be compared to All Known Subinterfaces: ArrayType, ByteValue, CharValue, ChronoLocalDate, ChronoLocalDateTime , Chronology, ChronoZonedDateTime , ClassType, Delayed, DoubleValue, Field, FloatVal
docs.oracle.com
Comparable 인터페이스는 compareTo(Object o) 를 Override해야하며, Comparator 객체는 compare(Object o1, Object o2)를 Override해주어야 한다. compareTo()는 비교하는 두 객체가 같으면 0을, 비교하는 값보다 작으면 음수를, 크면 양수를 반환하도록 구현해야한다.
Object 클래스의 equals는 모든 객체가 동일하게 가지고 있다. 만약 Comparable이나 Comparator인터페이스를 구현한 클래스는 equals()에 대한 오버라이딩이 필요할 수 있다.
equals Document : https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
Object (Java Platform SE 7 )
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. The general contract of fi
docs.oracle.com
기본적으로 Comparable을 구현한 클래스는 오름차순으로 정렬되어 있지만, Comparator인터페이스를 구현한 클래스는 내림차순 혹은 다른 기준으로 정렬되게 할 수 있다.
문자열들을 오름차순정렬, 대소문자 구분없는 오름차순정렬, 내림차순으로 정렬하는 예제들을 작성해보자.
import java.util.Arrays;
import java.util.Comparator;
//[Dog, cat, lion, tiger]
//[cat, Dog, lion, tiger]
//[tiger, lion, cat, Dog]
class ComparatorExample{
public static void main(String[] args){
String[] arr = {"cat","Dog","lion","tiger"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
// 대소문자 구분없이 정렬한다는 의미이다. 기본적으로 대문자가 소문자 앞에온다
Arrays.sort(arr,String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(arr));
Arrays.sort(arr, new Descending());
System.out.println(Arrays.toString(arr));
}
}
class Descending implements Comparator{
@Override
public int compare(Object o1, Object o2) {
//String 클래스는 기본적으로 Comparable을 구현하였기 때문에, instanceof의 결과는 true이다.
if(o1 instanceof Comparable && o2 instanceof Comparable){
Comparable c1 = (Comparable) o1;
Comparable c2 = (Comparable) o2;
return c2.compareTo(c1); // 역순정렬, c1.compareTo(c2) * -1 로 해도된다.
}
return -1;
}
}
'Language > Java' 카테고리의 다른 글
[Java] 람다식 (0) | 2022.03.16 |
---|---|
[Java] Maven설치하기(M1 mac) (0) | 2022.03.01 |
[Java]제네릭스(Generics) (0) | 2022.02.16 |
[Java] Collection FrameWork (0) | 2022.02.08 |
[Java] 컬렉션 프레임워크(Collection Framework) (0) | 2022.01.25 |