Java -- collection (Map interface and Collection interface)

1. Common Collections

The Map interface and the Collection interface are the parent interfaces of all collection frameworks

1. The Collection interface is the root interface of the collection class

There is no direct implementation class for this interface in Java, but it is inherited to generate two interfaces, namely Set and List

Set  cannot contain duplicate elements

List  is an ordered collection that can contain repeated elements and provides access by index

2. Map is another interface in the Java.util package

The Map interface and the Collection interface have nothing to do with each other, they are independent of each other, but they are all part of the collection class

Map contains key-value pairs. Map cannot contain duplicate keys, but can contain the same value

3、Iterator

All collection classes implement the Iterator interface, which is an interface for traversing the elements in the collection, mainly including the following three methods:

(1) Whether hasNext() has the next element

(2) next() returns the next element

(3) remove() deletes the current element

1. The sub-interfaces of the Collection interface include: Set interface and List interface​​​​​​
        The implementation classes of the Set interface mainly include: HashSet, TreeSet, LinkedHashSet, etc.

        The implementation classes of the List interface mainly include: ArrayList, LinkedList, Stack, and Vector, etc.
2. The implementation classes of the Map interface mainly include: HashMap, TreeMap, Hashtable, ConcurrentHashMap and
Properties

, etc.

Two, Map, List, Set interface and class introduction

1. List (ordered, repeatable)

The objects stored in the List are ordered and repeatable. The List focuses on the index and has a series of methods related to the index, so the query speed is fast. Because when inserting or deleting data into the list collection, it will be accompanied by the movement of subsequent data, so the speed of inserting and deleting data is slow.

2. Set (unordered, cannot be repeated)

The objects stored in the Set are unordered and cannot be repeated. The objects in the set are not sorted in a specific way, but simply added to the set.

3. Map (key-value pair, unique key, non-unique value)

The Map collection stores key-value pairs, the key cannot be repeated, and the value can be repeated. According to the key to get the value, when traversing the map set, first get the set set of the key, and then traverse the set set to get the corresponding value.

The comparison is as follows:

 

3. The underlying implementation of common collections 

The bottom layer of ArrayList is an array. 

The bottom layer of LinkedList is a doubly linked list. 

The underlying principle of HashMap is the same as that of HashTable. After Java 8 version, if the hash collision at the same location is greater than 8, the linked list 

into a red-black tree. 

The bottom layer of HashTable is a hash table composed of chain address method (that is, array + single-item linked list). 

The bottom layer of HashSet is HashMap. 

The bottom layer of LinkedHashMap is modified from HashMap, which contains a doubly linked list that maintains the insertion order. 

The bottom layer of TreeMap is a red-black tree. 

The bottom layer of LinkedHashSet is LinkedHashMap. 

The bottom layer of TreeSet is TreeMap. 

4. The difference between HashMap and HashTable

HashMap does not consider synchronization and is thread-unsafe; Hashtable uses the synchronized keyword and is thread-safe

HashMap allows both K/V to be null; the latter K/V does not allow to be null

5. The difference between ConcurrentHashMap and Hashtable

ConcurrentHashMap combines the advantages of both HashMap and HashTable. HashMap does not consider the same 

In the first step, HashTable considers the synchronization problem. But HashTable locks the entire structure every time it is executed synchronously. 

The way ConcurrentHashMap locks is slightly finer grained

6. Implementation principle of ConcurrentHashMap 

JDK1.7: [Array (Segment) + Array (HashEntry) + Linked List (HashEntry node)] 

ConcurrentHashMap (segmentation lock) divides the entire bucket array into segments (Segment), and each lock only locks 

Part of the data in the container, multi-threaded access to data in different data segments in the container, there will be no lock competition, improving concurrent access 

Ask rate. 

Segment is a reentrant lock ReentrantLock, which plays the role of lock in ConcurrentHashMap. 

HashEntry is used to store key-value pair data. 

JDK1.8 : Node array + linked list / red-black tree 

CAS+Synchronized is used to ensure the safety of concurrent updates, and the bottom layer still uses the storage structure of array+linked list+red-black tree 

structure

Seven, the difference between ArrayList and Vector 

Vector is thread safe, ArrayList is not thread safe. 

Vector grows to twice the original size when the data is full, and ArrayList grows to the original capacity when the data volume reaches half of the capacity 

1.5 times. 

Eight, the difference between ArrayList and LinkedList

LinkedList is based on linked list data structure; ArrayList is based on dynamic array data structure 

LinkedList is more efficient in inserting and deleting data, and ArrayList is more efficient in querying

9. What is the default initialization length of HashMap

The default length in JDK is 16, and both the default length and the expanded length must be a power of 2

10. Java collection framework

There are collections in every programming language, and the initial version of Java contains several collection classes: Vector, Stack, HashTable, and 

Array. With the widespread use of collections, Java 1.2 proposed a collection framework that includes all collection interfaces, implementations, and algorithms. exist 

The use of generics and concurrent collection classes while ensuring thread safety has been experienced in Java for a long time. It is also included in the Java Concurrency Package 

, blocking interfaces and their implementations. Some of the advantages of the collection framework are as follows: 

(1) Use core collection classes to reduce development costs instead of implementing our own collection classes. 

(2) Code quality improves with the use of rigorously tested collection framework classes. 

(3) By using the collection classes that come with the JDK, the cost of code maintenance can be reduced. 

(4) Reusability and operability. 

11. Generics in Collection Framework

Java 1.5 introduced generics, and all collection interfaces and implementations use it extensively. Generics allow us to provide collections with a 

to hold the object type, so if you add any elements of other types, it will report an error at compile time. This avoids the need to 

A ClassCastException occurs at runtime, because you will get an error message at compile time. Generics also make code more 

Clean, we don't need to use explicit conversion and instanceOf operator. It also has benefits at runtime, since no classes are generated 

type-checked bytecode instructions

12. Collection does not inherit from Cloneable and Serializable interfaces 

The Collection interface specifies a set of objects, the objects being its elements. How to maintain these elements by the specific implementation of Collection 

Decide now. For example, some Collection implementations such as List allow duplicate elements, while others such as Set do not. a lot of 

Collection implementations have a public clone method. However, it doesn't make sense to put it in all implementations of collections 

of. This is because Collection is an abstract representation. What matters is implementation. 

The semantics and meaning of cloning or serialization come into play when dealing with concrete implementations. Therefore, the specific implementation should determine 

determines how it is cloned or serialized, or whether it can be cloned or serialized. 

Authorize cloning and serialization in all implementations, ultimately resulting in less flexibility and more restrictions. A particular implementation should decide 

Determines whether it can be cloned and serialized

Thirteen, the Map interface does not inherit the Collection interface

Even though the Map interface and its implementation are part of the collections framework, a Map is not a collection and a collection is not a Map. therefore, 

It doesn't make sense for Map to inherit Collection and vice versa. 

If Map inherits the Collection interface, where do the elements go? Map contains key-value pairs, which provide extraction key or 

method for a collection of value lists, but it does not fit the "set of objects" specification. 

14. Iterator

The Iterator interface provides an interface for traversing any Collection. We can use iterator method from a Collection 

to get an iterator instance. Iterators replace Enumeration in the Java collections framework. Iterators allow the caller to iterate 

Remove elements during generation

15. The difference between Enumeration and Iterator interfaces

Enumeration is twice as fast as Iterator and also uses less memory. Enumeration is very basic, 

It also meets basic needs. However, Iterator is safer than Enumeration because when a collection is 

While being traversed, it prevents other threads from modifying the collection. 

Iterators replace Enumeration in the Java collections framework. Iterators allow the caller to remove elements from the collection, while 

Enumeration can't do it. The iterator method name has been improved to make its function clearer

Sixteen, the difference between Iterator and ListIterator

(1) We can use Iterator to traverse Set and List collections, while ListIterator can only traverse List. 

(2) Iterator can only traverse forward, while LIstIterator can traverse bidirectionally. 

(3) ListIterator inherits from the Iterator interface, and then adds some additional functions, such as adding an element, replacing 

Change an element, get the index position of the previous or following element

Seventeen, hashCode() and equals() methods

HashMap uses the hashCode() and equals() methods of the Key object to determine the index of the key-value pair. when we try 

These methods will also be used when getting values ​​from HashMap. If these methods are not implemented correctly, the 

In this case, two different Keys may produce the same hashCode() and equals() output, and HashMap will recognize 

because they are the same, and then overwrite them instead of storing them in different places. Likewise, all stored duplicates are not allowed 

The collection classes of complex data use hashCode() and equals() to find duplicates, so it is very important to implement them correctly. 

The implementation of equals() and hashCode() should follow the following rules: 

(1) If o1.equals(o2), then o1.hashCode() == o2.hashCode() is always true. 

(2) If o1.hashCode() == o2.hashCode(), it does not mean that o1.equals(o2) will be true. 

18. Can any class be used as the key of the Map ?

We can use any class as the key of the Map, but before using them, we need to consider the following points: 

(1) If a class overrides the equals() method, it should also override the hashCode() method. 

(2) All instances of the class need to follow the rules related to equals() and hashCode(). Please refer to these previously mentioned 

but. 

(3) If a class does not use equals(), you should not use it in hashCode(). 

(4) The best practice for user-defined key classes is to make them immutable, so that the hashCode() value can be cached 

Come and have better performance. Immutable classes also ensure that hashCode() and equals() will not change in the future, such that 

will solve the problem related to variable

Nineteen, choose HashMap or TreeMap

For operations such as inserting, deleting, and locating elements in the Map, HashMap is the best choice. However, if you need 

To traverse an ordered set of keys, TreeMap is a better choice. Based on the size of your collection, maybe 

Adding elements to HashMap will be faster, replace map with TreeMap for ordered key traversal

20. Which collection classes provide random access to elements? 

The ArrayList, HashMap, TreeMap, and HashTable classes provide random access to elements

21. Difference between queue and stack

Both stacks and queues are used to pre-store data. java.util.Queue is an interface, and its implementation class is packaged in Java 

middle. Queues allow first-in-first-out (FIFO) retrieval of elements, but not always. The Deque interface allows retrieval of elements from both ends 

white. 

A stack is similar to a queue, but it allows last-in-first-out (LIFO) retrieval of elements. 

Stack is a class that extends from Vector and Queue is an interface

Twenty-two, Collections class

java.util.Collections is a utility class containing only static methods that manipulate or return collections. It contains a collection of operations 

A polymorphic algorithm that returns a new collection backed by the specified collection and some other content. This class contains the collection framework algorithms 

Methods, such as binary search, sorting, shuffling and reversing, etc.

23. The difference between Comparable and Comparator interfaces

Comparable and Comparator interfaces are used to sort collections or arrays of objects. The Comparable interface is 

Used to provide a natural ordering of objects, we can use this to provide ordering based on a single logic. 

The Comparator interface is used to provide different sorting algorithms, we can choose the Comparator to use to match 

Sort a given collection of objects

Guess you like

Origin blog.csdn.net/MinggeQingchun/article/details/118360318