Looking to create and add sample data into a sorted set using CompareTo [closed]
문제
I would like to create a sorted set with some sample data using CompareTo.
Can you provide some sample coding on how to do this?
해결책
You need a compareTo method in your class that you want to compare with others, and have the class implement comparable:
public class TestObject implements Comparable{
private int a_number;
public int getNumber() {
return a_number;
}
public int compareTo(TestObject other) {
return getNumber() - other.getNumber();
}
}
You can now compare objects of this class with objects of the same class
다른 팁
List<MyObject> list = new List<MyObject>()
......
Collections.sort(list, new Comparator<MyObject>(){
public int compare(MyObject o1, MyObject o2) {
return o1.myValue.compareTo(o2.myValue);
}
});
I would start by reading
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
and then reading how to use it in TreeSet
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
제휴하지 않습니다 StackOverflow