Collection List, Set, Map in java

Collection

The collection includes the Collection and map interfaces, and the Collection is composed of two sub-interfaces, List and Set , and each sub-interface has its own different implementation class.
insert image description here

List interface (ordered, repeatable values)

List is an ordered Collection, using this interface can precisely control the insertion position of each element. Users can use the index to access the elements in the List, similar to an array. Lists allow identical elements.

Commonly used classes that implement the List interface are LinkedList, ArrayList, and Vector.

ArrayList class : It is the most commonly used List implementation class, which implements variable-sized arrays. It allows all elements, including null. ArrayList is not synchronized.

ArrayList (can be understood as a dynamic array)

  • add: add a single element

  • remove: delete the specified element

  • contains: Find whether the element exists

  • size: Get the number of elements

  • isEmpty: determine whether it is empty

  • clear: clear

  • addAll: add multiple elements

  • containsAll: Find whether multiple elements exist

  • removeAll: delete multiple elements

LinkedList class: LinkedList implements the List interface and allows null elements. In addition, LinkedList provides additional get, remove, and insert methods at the head or tail of LinkedList. These operations make LinkedList can be used as a stack (stack), queue (queue) or two-way queue (deque).
The underlying operation mechanism of LinkedList
(1) The bottom layer of LinkedList maintains a doubly linked list
(2) Two attributes first and last are maintained in LinkedList to point to the first node and last node respectively
(3) Each node (Node object) is maintained inside Prev, next, and item are three attributes, among which prev points to the previous node, and next points to the next node. Finally realize the doubly linked list.
(4) Therefore, the addition and deletion of elements of LinkedList is not done through arrays, which is relatively efficient.
(5) A simple two-way linked list:
insert image description here
Comparison between ArrayList and LinkedList:
ArrayList:
underlying structure: variable array;
efficiency of addition and deletion: low; efficiency of
modification and query: high;
LinkedList:
underlying structure: two-way linked list;
efficiency of addition and deletion : higher, appended through the linked list;
the efficiency of changing the query: higher;

How to choose between ArrayList and LinkedList:

  1. If we have many operations to check, choose ArrayList
  2. If we have many additions and deletions, choose LinkedList
  3. Generally speaking, in the program, 80%-90% are queries, so in most cases, ArrayList will be selected
  4. In a project, it is possible to choose flexibly according to the business. One module uses ArrayList, and the other module uses LinkedList.

Vector class:
Vector is very similar to ArrayList, but Vector is synchronized. Although the Iterator created by Vector has the same interface as the Iterator created by ArrayList, because Vector is synchronized, when an Iterator is created and is being used, another thread changes the state of the Vector (for example, adding or deleting some element), when the Iterator method is called, a ConcurrentModificationException will be thrown, so the exception must be caught.

traversal mode

Iterator Iterator:

  • The iterator is mainly used to traverse the elements in the Collection collection
  • All collection classes that implement the Collection interface have an iterator() method to return an object that implements the Iterator interface, that is, an iterator can be returned
  • It is only used to traverse the collection, and the Iterator itself does not store objects.

Enhanced for loop
can replace iterator iterator, features: Enhanced for is the simplified version of iterator in essence. Can only be used to iterate over collections or arrays.

for(元素类型 元素名:集合名或数组名){
    
    
	访问元素
}

Set interface (value cannot be repeated)

Set is a Collection that does not contain repeated elements , that is, any two elements e1 and e2 have e1.equals(e2)=false, and Set has at most one null element. Obviously, the Set constructor has a constraint that the incoming Collection parameter cannot contain duplicate elements.
Note: Mutable Objects must be handled with care. If a variable element in a Set changes its state causing Object.equals(Object)=true will cause some problems.

  1. Unordered (inconsistent order of addition and removal, no index)
  2. Duplicate elements are not allowed, so contain at most one null

The traversal method of the set interface

The same as the convenience of Collection, because the Set interface is a subinterface of the Collection interface

  1. Iterators can be used
  2. enhanced for
  3. Cannot use index to get

hashset

  1. Hashset implements the set interface
  2. hashset is actually hashmap
  3. Can store null values, but only one
  4. Hashset does not guarantee that the elements are in order , it depends on the hash, and then determines the result of the index
  5. There can be no duplicate elements/objects, as mentioned in the previous use of the set interface

The bottom layer of hashset is hashmap, and the bottom layer of hashmap is (array + linked list + red-black tree)

LinkedHashSet

The underlying data structure is a doubly linked list and a hash table, ordered.
The order of the elements is guaranteed by the linked list, and the uniqueness of the elements is guaranteed by the hash table.

TreeSet

The underlying data structure is a red-black tree, which implements sorting internally, and you can also customize the sorting rules.
Natural sorting and comparator sorting guarantee the ordering of elements. The uniqueness of elements is guaranteed based on whether the return value of the comparison is 0.

ArraySet

The underlying data structure is an array of doubles, ordered.

Map interface

Map does not inherit the Collection interface, and Map provides mapping from key to value. A Map cannot contain the same key, and each key can only map to one value. The Map interface provides three sets of views. The contents of a Map can be regarded as a set of keys, a set of values, or a set of key-value mappings.

jdk8

  1. Map and Collection exist side by side to save data Key-Value with mapping relationship
  2. Key and value in Map can be any reference type of data, which will be encapsulated into HashMap
  3. The key in Map is not allowed to be duplicated for the same reason as HashSet
  4. The value in the map can be repeated
  5. The key in the map can be null, and the value can also be null. Note that if the key is null, there can only be one, and if the value is null, there can be multiple
  6. The String class is often used as the key of the Map
  7. There is a one-way one-to-one relationship between key and value, that is, the corresponding value can always be found through the specified key
    ![
    ](https://img-blog.csdnimg.cn/cb904bf906ea4debbb3626c9325e58b1.png)

Common methods:

  1. put
  2. remove
  3. get
  4. size
  5. isEmpty
  6. clear
  7. containsKey

Map traversal method

  1. containsKey finds whether the key exists
  2. keySet gets all keys
  3. entrySet gets all relations kv
  4. values ​​get all values

summary:

  1. Common implementation classes of the Map interface: HashMap, Hashtable, Properties
  2. HashMap is the most frequently used implementation class of the Map interface
  3. HashMap stores data in the form of key-val pairs
  4. The key cannot be repeated, but the value can be repeated, allowing null keys and null values
  5. If the same key is added, the original key-val will be overwritten, which is equivalent to modification, (key will not be replaced, val will be replaced)
  6. Unlike HashSet, the order of mapping is not guaranteed, because the underlying layer is stored in the form of a hash table.
  7. HashMap does not implement synchronization, so it is not thread safe.
Hashtable类

Hashtable inherits the Map interface and implements a hash table for key-value mapping. Any non-null object can be used as key or value. Use put(key, value) to add data, and get(key) to remove data. The time overhead of these two basic operations is constant. Hashtable is synchronized.

HashMap class

HashMap is similar to Hashtable, except that HashMap is asynchronous and allows null, that is, null value and null key. But when HashMap is regarded as Collection (the values() method can return Collection), the time cost of iterating sub-operations is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations is very important, do not set the initialization capacity of HashMap too high, or the load factor is too low.

  1. The stored elements are key-value pairs: kv

  2. Neither the key nor the value of the hashtable can be null, otherwise a NullPointerException is thrown

  3. The use of hashtable is basically the same as that of hashmap

  4. hashtable is thread-safe, hashmap is thread-unsafe

Expansion mechanism:

properties

  1. The Properties class inherits from the Hashtable class and implements the Map interface, and also uses a key-value pair to store data.
  2. His use characteristics are similar to Hashtable
  3. Properties can also be used to load data from the xxx.properties file to the properties class object, and read and modify it
  4. Explanation: After work, the xxx.properties file is usually used as a configuration file. This knowledge point is given as an example in IO flow.

collection selection rules

  1. First determine the type of storage (a set of objects [single column] or a set of key-value pairs [double column])
  2. A set of objects [single column]: Collection interface

​Repeat allowed List

​Many additions and deletions LinkedList [The underlying layer maintains a doubly linked list]

​Change and check more: ArrayList [the bottom layer maintains a variable array of Object type]

​Duplicate not allowed Set

​Unordered : HashSet [the bottom layer is HashMap, which maintains a hash table (array + linked list + red-black tree)]

​Sorting : TreeSet

​Insert and remove in the same order: LinkedHashSet, maintain array + doubly linked list

  1. A set of key-value pairs: Map

Unordered keys: HashMap [the bottom layer is: hash table jdk7: array + linked list, jdk8: array + linked list + red-black tree]

​Key sorting: TreeMap

Key insertion and extraction are in the same order: LinkedHashMap

​Read file: Properties

Guess you like

Origin blog.csdn.net/weixin_44516623/article/details/128066675