Why should a Java class implement comparable?

后端 未结 10 772
忘掉有多难
忘掉有多难 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;
    }
    

提交回复
热议问题