0

I have a class States that is an object that contains a name, and a list of states that we consider edges. I would like to sort this list of edges by name, in both ascending and descending order. I had an idea of overriding the compareTo function and leveraging Collections.sort().

public class State { 
    private String name;
    private ArrayList<States> edges;      
    ...

    public ArrayList<States> getEdges(){
        return edges;
    }

    public int compareTo(State s, int type){
        switch(type){
            case 0: 
                // we want ascending order, return as normal
                return this.name.compareTo(s.getName());
            case 1:
                // we want descending order, negate our answer
                return -this.name.compareTo(s.getName());
        }
        return -1;
     }

Is it possible to use Collection.sort(), but be able to provide the 'type' parameter to specify whether I want ascending or descending order? If not, what are some other ways I can accomplish this?

Talen Kylon
  • 1,908
  • 7
  • 32
  • 60
  • 1
    *"If not, what are some other ways I can accomplish this?"* Just [reverse](http://stackoverflow.com/questions/3962766/java-reverse-list) the list. – Tom Feb 20 '16 at 20:28

1 Answers1

3

You could make the list descending by reversing it:

Collection<?> collection = ...;
Collections.reverse(collection);

PS: why is your class named States? From what I see the class represents a State...

NonameSL
  • 1,405
  • 14
  • 27