In the past example on Comparable Interface, we built Natural Sorting Order for our Product class by overriding the compareTo method. We did this sorting in the Product class itself. Then we used the Product as TreeSet Items. This means, does TreeSet support only one sorting? No, we can define custom sorting also. We can define it through a user class which signs the Comparator Interface and overrides its compare method. We can define one or many custom sorting orders using the Comparator Interface. For example, Sorting the product by its name in Ascending and descending order can be done through Java Comparator Interface.
Articles on Java programming language.
We used TreeSet class in the past example on the Integer boxed type. The TreeSet knows how to compare two Integer boxed type because the Java Integer class implements Comparable interface. For user-defined types, one should sign the the Comparable interface contract so that Java Collection class like TreeSet knows how to compare two objects and choose which one is bigger. The Comparable interface has a contract method compareTo which will study two objects and returns an integer. This integer value is helpful to know the object bigger or smaller or equal with the compared object. In this example, we will use the Java TreeSet to store Product objects.
The Java TreeSet class implements the SortedSet Interface. Before we move on to the TreeSet Collection class, we will study about the SortedSet interface and functionality it offers. Set interface is base for SortedSet interface, and a SortedSet gives all the functionality of the Set interface. We once saw the Set interface when we leant about the HashSet in HashSet Example. On top of the Set’s unique items claim, the SortedSet claims for Element Ordering.
Since SortedSet perform sorting, it needs to know how to compare two elements and say which one is big. Java types String and Boxed types Integer, Double etc. provide these comparisons via the Comparable Interface.
In the past Java HashSet example, we learnt about the Java HashSet and its Set implementation and how it keeps the uniqueness. Now, in this example, we will learn about the Buckets and how it aids quicker retrieval and search. These buckets improve the performance of search action and this example will research how these bucketing concepts work with HashSet Class and hashCode override of its stored object.
Before we learn about Java hashSet class, we will learn about the Set interface. Because the HashSet class implements Java Collection’s Set interface. The Set Interface ensures the implementing class to hold uniqueness in the collection. Means, it does not allow duplicate items. In Java Collection framework, the below classes implement the Set interface:
There were other classes as well. But here we listed frequently used ones. In this example, we will explore about the HashSet collection class.