Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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);
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top