JAVA/이론
[JAVA] 객체 비교
sirius
2021. 3. 22. 09:51
class ComparableFruit implements Comparable<ComparableFruit> {
private String name;
private int price;
public ComparableFruit(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
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(ComparableFruit compareFruit) {
//this가 먼저 앞에 있으면 ASC 비교할 대상이 먼저 앞에 잇으면 DESC
//return this.price - compareFruit.price;
return compareFruit.price - this.price;
}
}
Fruit[] fruits = new Fruit[6];
fruits[0] = new Fruit("kiwi", 100);
fruits[1] = new Fruit("mango", 300);
fruits[2] = new Fruit("pineapple", 500);
fruits[3] = new Fruit("grape", 700);
fruits[4] = new Fruit("banana", 400);
fruits[5] = new Fruit("apple", 200);
for(int i = 0; i < fruits.length; i++) {
System.out.print(fruits[i].getName() + " ");
}
System.out.println();
Arrays.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit o1, Fruit o2) {
String o1Name = o1.getName().toUpperCase();
String o2Name = o2.getName().toUpperCase();
return o1Name.compareTo(o2Name);
}
});
for(int i = 0; i < fruits.length; i++) {
System.out.print(fruits[i].getName() + " ");
}