Looking to create and add sample data into a sorted set using CompareTo [closed]
Pergunta
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?
Solução
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
Outras dicas
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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow