Dafference between ArrayList and HashSet - TongtongLan/Java GitHub Wiki

ArrayList和HashSet的主要区别在于一个是List实现,另一个是Set实现。 这意味着List数据结构和Set数据结构之间的所有差异也适用于这一对。 例如,List实现是有序的,它按照它们添加的顺序存储元素,而Set实现不提供这样的保证。 同样,由于List提供了随机访问,所以如果您知道索引,则可以直接访问任何元素,但Set不提供此类功能。 你需要遍历整个集合来访问任何元素。

Similarities ArrayList and HashSet

  • 都不是线程同步的

Both ArrayList and HashSet are non synchronized collection class and not meant to be used in multi-threading and concurrent environment. You can make ArrayList and HashSet synchronized by using

Collections.synchroinzedCollection()

just like we make ArrayList and HashSet read only other day.

  • 都可以使用迭代器访问集合中所有项

Both ArrayList and HashSet can be traversed using Iterator. This is in fact a preferred way if you want to perform operation on all elements.

  • 迭代器都是fail-fast的

they will throw ConcurrentModificationException if ArrayList or HashSet is modified structurally once Iterator has been created.

Differece between ArrayList and HashSet

  • 实现接口不同

First and most important difference between ArrayList and HashSet is that ArrayList implements List interface while HashSet implements Set interface in Java.

  • ArrayList允许插入重复项,HashSet则不允许

Another difference between ArrayList and HashSet is that ArrayListallow duplicates while HashSet doesn't allow duplicates. This is the side effect of fist difference and property of implementing List and Set interface.

  • ArrayList是有序集合,HashSet则是无序的(实现SortSet 接口除外)

Third difference between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.

  • 底层实现不同,ArrayList 是数组,HashSet则是维护了一个对HashMap对象的引用

Fourth difference between ArrayList and HashSet is that ArrayList is backed by an Array while HashSet is backed by an HashMap instance. See how HashSet internally works in Java for more details.

  • ArrayList提供get方法用于通过索引查找项,HashSet不提供get方法,只能通过迭代器访问集合中的项

Fifth difference between HashSet and ArrayList is that its index based you can retrieve object by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide get() method.