Consider implementing Comparable

Comparable interface provides compareTo method which is similar with Object’s equals method, except that it permits order comparisons in addition to simple equality comparisons, and it is generic. By implementing Comparable, a class indicates that its instances have a natural ordering. Sorting an array of objects that implement Comparable is as simple as this:


It is similarly easy to search, compute extreme values, and maintain automatically sorted collections of Comparable objects. For example, the following program which relies on the fact that String implements Comparable, prints an alphabetized list of its command-line arguments with duplicates eliminated:

public class WorldList {
  public static void main(String[] args) {
    Set set = new TreeSet<>();
    Collections.addAll(s, args);

The general contract of the compareTo method is similar to that of equals.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.