import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Descending_Obj_Sort {
public static void main(String[] args) {
ArrayList<Test> data = new ArrayList<Test>();
/*임의로 Test 객체 데이터 삽입*/
data.add(new Test("name3", 3));
data.add(new Test("name1", 7));
data.add(new Test("name2", 5));
/*Test Class 변수 Name 기준 내림차순 정렬하기*/
NameDecending nameDecending = new NameDecending();
Collections.sort(data, nameDecending);
for (Test temp : data) {
System.out.print(temp + " ");
}
System.out.println("\n");
/*Test Class 변수 Point 기준 내림차순 정렬하기*/
PointDecending pointDecending = new PointDecending();
Collections.sort(data, pointDecending);
for (Test temp : data) {
System.out.print(temp + " ");
}
System.out.println();
}
}
/*Test객체의 name을 기준으로 내림차순 정렬하기*/
class NameDecending implements Comparator<Test> {
@Override
public int compare(Test a, Test b) {
String temp1 = a.getName();
String temp2 = b.getName();
return temp2.compareTo(temp1);
/*return b.getName().compareTo(a.getName());*/
}
}
/*Test객체의 Point를 기준으로 내림차순 정렬하기*/
class PointDecending implements Comparator<Test> {
@Override
public int compare(Test a, Test b) {
Integer temp1 = a.getPoint();
Integer temp2 = b.getPoint();
return temp2.compareTo(temp1);
}
}
class Test {
private String name;
private int point;
public Test(String name, int point) {
this.name = name;
this.point = point;
}
public String getName() {
return this.name;
}
public int getPoint() {
return point;
}
@Override
public String toString() {
return "[name=" + name + ", point=" + point + "]";
}
}