Java HashSet is very powerful Collection type when you want a collection of unique objects. HashSet doesn’t allow duplicate elements. HashSet also gives constant time performance for insertion, removal and retrieval operations. It is also important to note that HashSet doesn’t maintain any order. So, It is recommended to use HashSet if you want a collection of unique elements and order of elements is not so important. If you want your elements to be ordered in some way, you can use LinkedHashSet or TreeSet.
In this Java article, we will see one real time example of HashSet.
Let’s create one HashSet of Student records where each Student record contains three fields – name, rollNo and department. In these, rollNo will be unique for all students.
Let’s create Student class with three fields – name, rollNo and department.
You can notice that hashCode() and equals() methods are overrided in the above class so that two Students objects will be compared solely based on rollNo. That means, two Student objects having same rollNo will be considered as duplicates irrespective of other fields.
Create one HashSet object containing elements of Student type.
No comments:
Post a Comment