简体   繁体   English

由HashSet备份的列表

[英]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 . 我需要按照添加顺序将对象存储在集合中,这就是为什么我需要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 . 与其每次都迭代该列表,不如拥有一个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? 通过添加HashSet字段来扩展ArrayList?

  2. implement one of the Java collection interfaces (List or Set)? 实现Java集合接口之一(列表或集合)?

  3. simply create a new class with two fields - ArrayList and HashSet? 只需创建一个具有两个字段的新类-ArrayList和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). 第一个选项有一个缺点-我不需要所有的ArrayList方法,因此我必须重写所有方法,以便我的类的用户不会调用只会使事情搞砸的基类方法(例如,则可以从列表中删除一个对象,但该对象仍将存在于集合中)。 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. 同样,对于2,我真的必须实现接口的所有方法。

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. 我想拥有List接口具有的所有add方法。 - LinkedHashSet is not an option . -LinkedHashSet不是一个选项

You could use a LinkedHashSet , which a Set implementation that ensures that iteration order is the same order you added elements in. 您可以使用LinkedHashSet ,它是一个Set实现,可确保迭代顺序与添加元素的顺序相同。

Hash table and linked list implementation of the Set interface, with predictable iteration order. Set接口的哈希表和链表实现,具有可预测的迭代顺序。 ... 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. 使用LinkedHashSet维护相遇顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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