简体   繁体   中英

List backed up by a HashSet

I need to store objects in a collection in the order they were added, that's why I need a List . However, the list should contain no duplicates. I also need to quickly determine if an object already exists in the collection. Instead of iterating the list every time, it would be better to have something like a HashSet . I can quickly both find and add elements and preserve the insertion order.

The question is - should I:

  1. extend ArrayList by adding a HashSet field?

  2. implement one of the Java collection interfaces (List or Set)?

  3. simply create a new class with two fields - ArrayList and HashSet?

The 1st option has the disadvantage - I don't need all of the ArrayList methods, so I'd have to override all of them so that users of my class don't call base class methods that would simply mess things up (for instance, one could remove an object from the list but the object would still exist in the set). And there's no way to remove the base class methods (except from overriding it and throwing an exception).

Similarly for 2, I'd really have to implement all methods of the interface.

The 3rd option looks the best to me, but it makes the code implementation dependent, because my class doesn't implement any interface.

What should I do in this case? I'd like to have all add methods the List interface has. - LinkedHashSet is not an option .

You could use a LinkedHashSet , which a Set implementation that ensures that iteration order is the same order you added elements in.

Hash table and linked list implementation of the Set interface, with predictable iteration order. ... This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order) .

No need to implements anything on your own. Use LinkedHashSet which maintains encounter order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM