As you already know, LinkedHashSet is an ordered version of HashSet. That means, HashSet doesn’t maintain any order where as LinkedHashSet maintains insertion order of the elements. LinkedHashSet uses doubly linked list internally to maintain the insertion order of it’s elements. We have seen this in How LinkedHashSet Works Internally In Java?. As LinkedHashSet maintains doubly linked list (along with HashMap), the performance of LinkedHashSet is slightly slower than the HashSet. But, LinkedHashSet will be very useful when you need a collection of elements placed in the order they have inserted. We will see one such example of LinkedHashSet in this article.
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.
理解:LinkedHashSet是HashSet的有序版本,也就是它能够保存元素的插入顺序.LinkedHashMap使用双向链表来保存元素的插入顺序的.虽然性能上不如HashSet,但它可以保存元素的插入顺序.加入你需要根据客户到达时间来为客户服务,而且客户副本是不允许的,对于这样的需求,LinkedHashSet是最合适的.
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.
理解:Customer类复写了equal和hashcode函数,Customer对象自会根据Id来比较是否相等.这意味着拥有相同id的客户会被认为是重复的元素,他们不会被加入到池中.
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.