문제

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);
            }
        });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top