Comparable interface functions provide a comparison object size, the object implements compareTo method to compare the size of this interface class provides the interface through.
This method returns an int type, three cases.
- Returns a positive number, the current object is greater than the target object
- Returns negative, the current object is less than the target object
- Returns 0, the current object is equal to the target object
TreeSet object provides a sorting function (by default ascending order), if the storage container is a custom class that will implement these features for Comparable TreeSet object-size comparison, otherwise an error.
public class TestCompareTo implements Comparable<TestCompareTo> { private Integer a = null; public TestCompareTo(Integer a) { this.a = a; } public Integer getA() { return a; } @Override public int compareTo(TestCompareTo o) { return this.a > o.a ? -1 : (this.a == o.a ? 0 : 1); } }
public class Test{ public static void main(String[] args) { //test TreeSet Set<TestCompareTo> set = new TreeSet<>(); set.add(new TestCompareTo(-10)); set.add(new TestCompareTo(-20)); set.add(new TestCompareTo(-30)); set.add(new TestCompareTo(0)); set.add(new TestCompareTo(10)); set.add(new TestCompareTo(-100)); Iterator iterator = set.iterator(); while(iterator.hasNext()){ TestCompareTo tmp = (TestCompareTo) iterator.next(); System.out.println(tmp.getA()); } } }