Comparable과 Comparator는 모두 컬렉션의 요소를 정렬하는 데 사용할 수 있는 인터페이스입니다. 비교자 인터페이스는 java.util 패키지에 속하고 비교자는 java.lang 패키지에 속합니다. 비교자 인터페이스는 제공된 두 개의 객체를 사용하여 컬렉션을 정렬하는 반면, 비교 가능한 인터페이스는 "이"를 비교하여 제공된 하나의 객체를 참조합니다.
| Sr. 아니요. | 키 | 비교 | 비교기 |
|---|---|---|---|
| 1 | 메소드 | 비교할 수 있는 인터페이스에는 compareTo(Object a) 메서드가 있습니다. | 비교기에는 compare(Object o1, Object O2) 메서드가 있습니다. |
| 2 | 정렬 용도 | Collection.sort(List) 메서드는 Comparable 유형 개체의 컬렉션을 정렬하는 데 사용할 수 있습니다. | Collection.sort(List, Comparator) 메서드는 Comparator 유형 개체의 컬렉션을 정렬하는 데 사용할 수 있습니다. |
| 3 | 정렬 순서 | Comparable은 단일 정렬 순서를 제공합니다. | 비교기는 다중 정렬 순서를 제공합니다. |
| 4 | 패키지 | 비교 가능한 인터페이스는 java.lang 패키지에 속합니다. | 비교기 인터페이스는 java.util 패키지에 속합니다. |
비교의 예
public class ComparableExample {
public static void main(String[] args) {
List<Laptop> laptopList = new ArrayList<>();
laptopList.add(new Laptop("HCL", 16, 800));
laptopList.add(new Laptop("Apple", 8, 100));
laptopList.add(new Laptop("Dell", 4, 600));
Collections.sort(laptopList);
for (Laptop lap : laptopList) {
System.out.println(lap.getRam());
}
}
}
public class Laptop implements Comparable<Laptop> {
String name;
int ram;
int price;
public Laptop(String name, int ram, int price) {
super();
this.name = name;
this.ram = ram;
this.price = price;
}
public String getName() {
return name;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int compareTo(Laptop o) {
if (this.ram > o.getRam())
return 1;
else {
return -1;
}
}
} 출력
4 8 16
비교기의 예
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Laptop implements Comparator {
String name;
int ram;
int price;
public Laptop(String name, int ram, int price) {
super();
this.name = name;
this.ram = ram;
this.price = price;
}
public String getName() {
return name;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int compare(Laptop o1, Laptop o2) {
if (o1.getRam() < o2.getRam()) {
return -1;
}else if (o1.getRam() > o2.getRam()) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
List laptopList = new ArrayList<>();
laptopList.add(new Laptop("HCL", 16, 800));
laptopList.add(new Laptop("Apple", 8, 100));
laptopList.add(new Laptop("Dell", 4, 600));
Comparator com = (Laptop o1, Laptop o2) -> o1.getName().compareTo(o2.getName());
Collections.sort(laptopList, com);
for (Laptop lap : laptopList) {
System.out.println(lap.getName());
}
}
} 출력
Apple Dell HCL