public interface Comparator {
int compare(Object o1, Object o2);
boolean equals(Object obj); // equals를 overriding 하라는
}
public interface Comparable {
int compareTo(Object o);
}
Integer에 구현된 comparable
public final class Integer extends Number implements Comparable {
public int compareTo(Integer anotherInteger){
int v1 = this.value; // 나 자신
int v2 = anotherInteger.value; // 받은 값
return (v1 < v2 ? -1 : (v1==v2? 0:1));
}
}
import java.util.*;
public class ComparatorAndComparable {
public static void main(String[] args) {
String[] animal = {"cat", "Dog", "lion", "Eagle", "tiger", "duck","ael","Ant"};
Arrays.sort(animal);
System.out.println(Arrays.toString(animal));
Arrays.sort(animal, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(animal));
// Arrays.sort(animal, Comparator.reverseOrder());
Arrays.sort(animal, (o1, o2)-> o2.compareTo(o1));
System.out.println(Arrays.toString(animal));
int[] intArr = {1, 2, 3, 4, 7, 0, -2, 4};
Arrays.sort(intArr);
System.out.println(Arrays.toString(intArr));
ArrayList<Integer> intList = new ArrayList<>(List.of(1, 2, 3, 4, 7, 0, -2, 4));
for (Integer i : intList) System.out.print(i+",");
System.out.println();
Collections.sort(intList);
for (Integer i : intList) System.out.print(i+", ");
System.out.println();
intList.sort((o1, o2) -> o2.compareTo(o1));
for (Integer i : intList) System.out.print(i+", ");
}
// private static class Descending implements Comparator<Object> {
// @Override
// public int compare(Object o1, Object o2) {
// if (o1 instanceof Comparable && o2 instanceof Comparable) {
// Comparable c1 = (Comparable) o1;
// Comparable c2 = (Comparable) o2;
// return c2.compareTo(c1);
// }
// return -1;
// }
// }
}
'kotlin > java' 카테고리의 다른 글
무작위로 4개의 char를 추출해서 정렬 (0) | 2023.01.06 |
---|---|
LocalDateTime 예제 (0) | 2023.01.06 |
Arrays class (0) | 2023.01.06 |
Stack & Queue (0) | 2023.01.06 |
LinkedList (0) | 2023.01.06 |