java Collection/Map selection

1.Collection interface

The Collection interface implements the Iterator interface, so all implementation classes of the Collection interface can use iterators for iteration.

The Collection interface mainly has two important sub-interfaces, List and Set.
The main features of List are: ordering, repeatable values, and support for index access.
The main feature of Set is: the value cannot be repeated.

Common implementation classes of List:

  1. Vector : dynamic array implementation, thread-safe .
  2. ArrayList : Dynamic array implementation, non-thread safe, high efficiency .
  3. LinkedList : Doubly linked list implementation, non-thread-safe, high addition and deletion efficiency .

When considering List selection, ArrayList is considered by default. If there are many additions and deletions, select LinkedList. If there are many access operations, select Vector (thread-safe) or ArrayList (non-thread-safe).

Set common implementation classes:

  1. HashSet : The implementation is the same as HashMap, but the iteration order is not guaranteed .
  2. LinkedHashSet : The implementation is the same as LinkedHashSet, which can ensure that the iteration order and insertion order are the same .
  3. TreeSet : Red-black tree implementation, comparison rules can be set based on the incoming Comparator object, and the elements are arranged in the order of the rules .

If you need a fast Set that has nothing to do with order issues, choose HashSet. If you need to sort the Set, choose TreeSet. If you need to read and input in the same order, choose LinkedHashSet.
Insert image description here

2.Map interface

The Map interface does not implement the Iterator interface, so iterator cannot be used for iteration. Iteration should use entrySet (get the key-value pair set), keySet (get the key set).

Common Map implementation classes:

  1. HashMap : implemented by hash table + linked list + red-black tree, with high efficiency.
  2. LinkedHashMap : Based on HashMap, a doubly linked list is added to maintain the order in which elements are added, ensuring that the iteration order is the same as the insertion order .
  3. TreeMap : Red-black tree implementation, comparison rules can be set based on the incoming Comparator object, and the elements are arranged in the order of the rules .
  4. HashTable : The implementation is consistent with HashMap, thread-safe , and null cannot be used as key or value.
  5. Properties : Mainly used to process .properties configuration files.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44866921/article/details/132458167