Why should a Java class implement comparable?

后端 未结 10 609
忘掉有多难
忘掉有多难 2020-11-22 13:14

Why is Java Comparable used? Why would someone implement Comparable in a class? What is a real life example where you need to implement comparable

相关标签:
10条回答
  • 2020-11-22 13:34

    OK, but why not just define a compareTo() method without implementing comparable interface. For example a class City defined by its name and temperature and

    public int compareTo(City theOther)
    {
        if (this.temperature < theOther.temperature)
            return -1;
        else if (this.temperature > theOther.temperature)
            return 1;
        else
            return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 13:45

    Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:

    class AirlineTicket implements Comparable<Cost>
    {
        public double cost;
        public int stopovers;
        public AirlineTicket(double cost, int stopovers)
        {
            this.cost = cost; this.stopovers = stopovers ;
        }
    
        public int compareTo(Cost o)
        {
            if(this.cost != o.cost)
              return Double.compare(this.cost, o.cost); //sorting in ascending order. 
            if(this.stopovers != o.stopovers)
              return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
            return 0;            
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:46

    Quoted from the javadoc;

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

    Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

    Edit: ..and made the important bit bold.

    0 讨论(0)
  • 2020-11-22 13:49

    Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".

    Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?

    TreeSet<Integer> m = new TreeSet<Integer>(); 
    m.add(1);
    m.add(3);
    m.add(2);
    for (Integer i : m)
    ... // values will be sorted
    

    But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:

    public class District {
      String zipcode; 
      Double populationDensity;
    }
    

    Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:

    public class District implements Comparable<District>{
      String zipcode; 
      Double populationDensity;
      public int compareTo(District other)
      {
        return populationDensity.compareTo(other.populationDensity);
      }
    }
    

    Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.

    Basically the ordering logic has to exist somewhere. That can be -

    • in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)

    • supplied in an external comparator, as in the example above.

    0 讨论(0)
提交回复
热议问题