Let’s consider that you want to create a pool of customers placed in the order they have arrived. Assume that it is also mandatory that duplicate customers must not be allowed. For such requirements, LinkedHashSet is the best suitable. In this article, we will try to implement this example using LinkedHashSet class.
理解:
Let’s create Customer class with two fields – name and id.
You might have observed that equals() and hashCode() methods in the above class are overrided so that Customer objects will be compared solely based on id. That means two Customer objects having same id will be considered as duplicates and they will not be allowed in the pool.
Create one LinkedHashSet object containing elements of Customer type.
Add some elements to this set.
set.add(new Customer("Jack", 021)); set.add(new Customer("Peter", 105)); set.add(new Customer("Ramesh", 415)); set.add(new Customer("Julian", 814)); set.add(new Customer("Avinash", 105)); //Duplicate Element set.add(new Customer("Sapna", 879)); set.add(new Customer("John", 546)); set.add(new Customer("Moni", 254)); set.add(new Customer("Ravi", 105)); //Duplicate Element
Iterate through this LinkedHashSet.
Output will be,
You can notice that Customer objects are placed in the order they are inserted into the set and also duplicate elements are avoided.
Below is the code for the whole program.