2. JAVA [Collection]

Article Directory

The advantages of the collection framework?

  1. Use core collection classes to reduce development costs
  2. Reusability and operability

What are the advantages of generics in the collection framework?

  1. Generics allow us to provide a collection of object types that can be accommodated. Therefore, if you add any elements of other types, compilation errors will occur. This avoids ClassCastException at runtime.
  2. Generics make the code clean, without the need to use explicit conversion and instanceOf operators. It also brings benefits to the runtime, because no bytecode instructions for class detection are generated.

What are the basic interfaces of the JAVA collection framework?

Collection is the root interface of the collection hierarchy. A collection represents a group of objects, and these objects are its elements:

  1. Set: is a set that cannot contain repeated elements
  2. List: is an ordered collection that can contain repeated elements. You can use indexes to access elements. You can think of it as an array whose length is dynamically expanded

Map is an object that maps key to value. A Map cannot contain duplicate keys, and each key can map at most one value

There are some other interfaces, such as: Queue, Dequeue, SortedSet, SortedMap and Listlterator

Why does the Map interface not inherit the Collection interface?

  1. Map is not a collection
  2. If Map inherits Collection, Map contains key-value pairs, which is not suitable for a set of object specifications

The difference between Collection and Collections?

  1. Collection, is the superior interface of the collection class, the main interfaces inheriting from him are Set and List
  2. Collections is a tool class for collections. It provides a series of static methods to implement operations such as searching, sorting, and thread safety on various collections

What are the general algorithms in the collection?

  1. Sort and search
  2. The Collections class contains the implementation of these methods. Most algorithms operate on List, but some are available for all types of collections. Some algorithms include sorting, searching, mixing, maximum and minimum

Data interface such as collection framework

List:

  1. ArrayList: Object array
  2. Vector: Object array
  3. LinkedList: doubly linked list (circular linked list before jdk6, jdk7 cancels the cycle)

Map:

  1. HashMap: Before JDK8, it is composed of array + linked list. Array is the theme of HashMap. Linked list is mainly used to solve the problem of hash collision.
    After JDK8, there is a change in the resolution of hash conflict. When the length of the linked list is greater than the threshold (default When it is 8), convert the linked list into a red-black tree to reduce the search time
  2. LinkedHashMap: LinkedHashMap inherits from HashMap, and all the bottom layers are still based on the zipper hash structure, which is composed of arrays and linked lists or red-black trees. In addition, LinkedHashMap adds a doubly linked list based on the above structure, so that the above interface can maintain the insertion order of key-value pairs. At the same time, through corresponding operations on the linked list, the access sequence related logic is realized
  3. HashTable: composed of array + linked list, the array is the main body of the HashMap, the linked list is to solve the Hash conflict
  4. TreeMap: Red-black tree (self-balanced sorting binary tree)

Set:

  1. HashSet: unordered, unique, based on HashMap, the bottom layer uses HashMap to store elements
  2. LinkedHashSet: inherits HashSet, and its internal is realized through LinkedHashMap
  3. TreeSet: ordered, unique, red-black tree

What is an iterator?

The Iterator interface provides many methods for iterating over collection elements. Each collection class contains iteration methods that can return iteration instances. The iterator can delete the underlying element during the iteration process, but it cannot directly call the remove method of the collection class to delete it. You can call the remove method of the iterator to delete

What is the difference between Iterator and ListIterator?

  1. Iterator can be used to traverse Set and List collections, but ListIterator can only be used to traverse List
  2. Iterator can only traverse the collection forward, and ListIterator can be forward or backward
  3. ListIterator inherits the Iterator interface and contains other functions. For example: add elements, replace elements, get the index of the previous element and the next element, etc.

What is the difference between fail-fast and fail-safe?

Different from ConcurrentModification exception:

  1. Fast failure: When you iterate a collection, if another thread is modifying the collection you are accessing, a ConcurrentModification exception will be thrown. All under the java.util package fail fast
  2. Security failure: When you go back to the bottom collection to make a copy during iteration, all changes to the upper collection will not be affected, and ConcurrentModification exceptions will not be thrown. All under the java.util.concurrent package are safe to fail

How to delete an element in List?

  1. Use Iterator, the order is downward, if the element is found, use the remove method to delete
  2. Traverse the List in reverse order, if an element is found, use the remove method to delete

What is the difference between Enumeration and Iterator interfaces?

  1. In contrast, Enumeration is 2 times faster and takes up less memory
  2. Iterators are safer because other threads cannot modify the collection objects that the current iterator traverses. At the same time, Iterators allow the caller to delete elements from the underlying collection, Enumeration cannot be completed

Concrete implementation of Iterator interface

  1. fail-fast代表:ArrayList
  2. fail-safe代表:CopyOnWriteArrayList

The difference between Comparable and Comparator?

  1. The Comparable interface, under the java.lang package, is used to compare the current object with other objects, so it has a CompareTo method for sorting. Parameter 1
  2. The Comparator interface, under the java.util package, is used to pass in two objects for comparison, so there is a compare method for sorting. 2 parameters

The difference between List and Set?

Both List and Sert inherit the Collection interface

  1. List features: the elements are placed in order, can be repeated, n'li supports for loops, and iterators can also be used to traverse through subscripts
  2. Set features, elements are placed in disorder and cannot be repeated. Repeated elements will be overwritten. Although placed in disorder, the position of the element in the Set is fixed, which is determined by the hashcode of the element. It can only be traversed by iteration

List and Set comparison:

  1. Set: The efficiency of retrieving the specified element is high, and the efficiency of deletion and insertion is high. Insertion and deletion may cause the element position to change
  2. List: Similar to an array, the list can grow dynamically, the efficiency of finding the specified element is low, and the efficiency of inserting and deleting the specified element is low, because it may cause other element positions to change

If it is random access, list will be faster than set

What is the difference between Array and ArrayList? When is it appropriate to use Array?

  1. Array can hold basic types and objects, while ArrayList can only hold objects
  2. Array is a specified size, while the size of ArrayList is fixed and can be automatically expanded
  3. Array does not provide as versatile as Arraylist, such as addAll, removeAll and iterator, etc.

When is Array more suitable

  1. If the size of the list is fixed, most cases are storage and traversal
  2. For traversing collection data types, although Collections uses auto-boxing to ease the coding task, working on lists of basic types of specified sizes will also become very slow
  3. How do you want to use a multi-dimensional array, using [][] is more convenient than list

What is the difference between ArrayList and LinkedList?

ArrayList:
advantage: dynamic array, because the address is continuous, the efficiency of query operation will be higher if stored.
Disadvantage: because the address is continuous, ArrayList needs to move data, so the efficiency of insert and delete operations is relatively low

LinkedList:
Advantages: Based on the data structure of the linked list, the address is arbitrary, so there is no need to wait for a continuous address when opening up the memory space. For adding and deleting operations, it is more dominant. It is suitable for scenes
that require head and tail operations or insert a specified position. Disadvantage: Because the pointer needs to be moved, the query operation performance is relatively low

What is the difference between ArrayList and Vector?

Both are implemented by arrays, and there are three main differences:

  1. Vector has synchronized keyword in many methods, which is multi-thread safe, while ArrayList is not
  2. Both use linear continuous space to store elements, but when the space is insufficient, the growth methods of the two classes are different
  3. Vector can set growth factor, but ArrayList cannot

Application scenario analysis:

  1. Regardless of thread safety, using ArrayList is more efficient, but in fact CopyOnWriteArrayList is often used if thread safety is
  2. If the number of elements in the collection is greater than the length of the collection array, using a relatively large amount of data in the collection, using Vector has certain advantages. In this case, it is more appropriate to use linkedList

The difference between HashMap and HashTable?

  1. Different inheritance: HashTable inherits Dictionary, HashMap inherits Map interface
  2. HashMap allows null values, HashTable does not allow
  3. HashTable thread safety, HashMap thread safety
  4. The iteration of HashMap fails quickly, while HashTable is not
  5. Expansion is not the same. The expansion of HashMap is an exponential size of 2 each time, while HashTable is old*2+1

Generally, it is not recommended to use HashTable now, and ConcurrentHashMap can be used instead in a multi-threaded environment

The difference between HashSet and HashMap?

  1. Set is a linear structure, and the value cannot be repeated. HashSet is the hashsh implementation of Set. The value in Hashset cannot be repeated is realized by the key of HashMap
  2. Map is a key-value pair mapping, which can be empty. HashMap is the hash implementation of Map. The uniqueness of the key is determined by the uniqueness of the key value hashcode, and the value value is a linked list structure, because different key values ​​may exist The same hashcode, so the value value needs to be a linked list structure

What they have in common is the uniqueness of the hash algorithm. They cannot hold basic types, only objects

The difference between HashSet and TreeSet?

The difference between b?

  1. HashSet is implemented with a hash table, so its elements are unordered. The time complexity of adding and deleting is O(1)
  2. TreeSet is implemented with a tree structure, so it is ordered. The time of adding and deleting fu'za'du
    is O(logn)

Corresponding to insert and delete operations in the Map, HashMap is the best choice.
If you need to traverse an ordered key, TreeSet is the best choice.
Based on the size of your Collection, it may be faster to add elements to the HashMap, then Replace HashMap with TreeMap for orderly key traversal

The difference between HashMap and ConcurrentHashMap?

ConcurrentHashMap is a thread-safe HashMap implementation. The main differences are as follows:

  1. ConcurrentHashMap separates the entire bucket array into segments, and then uses locks to protect each segment. Compared with HashTable's syn keyword lock, the granularity is finer and the concurrency performance is better. HashMap has no lock mechanism and is not thread-safe

After JDK8, ConcurrentHashMap enabled a new way to achieve, using CAS algorithm
2. HashMap key-value pairs allow null, ConcurrentHashMap does not allow

What are queues and stacks, and list their differences?

Both are used to store data.
1.java.util.queue is an interface, and its implementation class is in the java concurrent package.
The queue allows first-in-first-out (FIFO) to retrieve elements. The
Deque interface allows to retrieve elements from both ends
. 2. The stack is similar to a queue, but it allows last-in-first-out (LIFO) retrieval of elements.
Stack is a class that extends from Vecctor, while Queue Is an interface

How does HashMap work?

The two most commonly used structures in Java are arrays and analog pointers (references). HashMap is also, so HashMap is a linked list hash, HashMap is based on the principle of hasing:

  1. Find an element in the array by hashcode
  2. Use the equals method of key to traverse the linked list to find the value corresponding to the key

What happens when the hashcode of two objects is the same?

  1. When the hashcode is the same, so their bucket positions are the same, and a hash collision occurs
  2. Because hashMap uses a linked list to store objects, this entry (Map.Entry object containing key-value pairs) will be stored in the linked list

What is the importance of the HashCode and equals methods?

HashMap uses the hashcode and equals methods of the key object to determine the key-value index. When we try to get values ​​from HashMap, these methods will be used

  1. If these two methods are not used correctly, two different keys may produce the same hashcode and equals output. HashMap will consider them the same and overwrite them instead of storing them in different places.
  2. Similarly, if collection classes that store duplicate data are not allowed to use hashcode and equals to find duplicates, it is very important to use them correctly. The implementation should follow the following rules:

If o1.equals(o2), then o1.hashcode()==o2.hashcode(), always true.
If o1.hashcode()==o2.hashcode(), I don’t think o1.equals(o2) will Is true

What is the default capacity of HashMap?

The default is 16, and the load factor is 0.75. That is, HashMap is filled with 75% of the busket

What order of HashMap implementation classes are there?

  1. LinkedHashMap is based on the order in which the elements enter the collection or the order in which they are accessed
  2. TreeMap is based on the inherent order of elements.

Can any class be used as the key of Map?

Yes, but you need to consider the following points:

  1. If the class overrides the equals method, it should also override the hashCode method
  2. It is best to use an immutable class as the key. In this way, the hashcode can be cached and have better performance. It can also ensure that the future hashcode and equals will not change. Therefore, String and Integer are used as hashMap keys.

Why is the length of HashMap a power of 2?

In order to make the access of HashMap efficient, there are as few collisions as possible, that is, to distribute the data evenly, and the length of each linked list/red-black tree is roughly the same.
How should this algorithm be designed?
Remainder operation:
1. Remainder (%) If the divisor is a power of 2, it is equivalent to the AND (&) operation of subtracting one from the divisor, that is, (hash%length is leng't== hash & (length -1)) The premise is that length is 2 to the nth power
. 2. Using binary operation &, relative to% can improve the efficiency of calculation.
Therefore, the length of HashMap is the power of 2

How does HashSet work?

HashSet, when we create a HashSet object, a map object will also be created inside, and all subsequent HashSet operations are actually based on the encapsulation on this map

How does HashSet check for duplicates?

When you add an object to a HashSet, HashSet will first calculate the object's hashcode value to determine where the object is added, and colleagues will also take notes with the hashcode values ​​of other added objects

  1. If there is no identical hashcode, hashset will assume that the object does not appear repeatedly
  2. If an object with the same hashcode value is found, the equals method will be called to check whether the object with the same hashcode is really the same. If the two are the same, hashset will not allow the join operation to succeed; if the two are different, hashset will let Join operation succeeded

What is Java Priority Queue?

It is an unbounded queue of priority heap, and its elements are arranged in order in their natural order

  1. When it is created, we can provide a comparator Comparator to be responsible for the sorting of the elements in PriorityQueue
  2. Null elements are not allowed, objects that do not provide natural ordering, and objects without any associated Comparator are not allowed
  3. It is not thread-safe, and it requires o(log(n)) time complexity to perform enqueue and dequeue operations

The difference between poll and remove methods?

  1. poll method, it will return empty when the element fails to get
  2. remove method, an exception will be thrown when it fails

What is the difference between LinkedHashMap and PriorityQueue?

  1. priorityqueue guarantees that the highest or lowest priority element is always at the head of the queue, and the order maintained by linkedhashmap is the order in which the elements are inserted
  2. When traversing a priorityqueue, there is no order guarantee, but linkedhashmao guarantees that the traversal order is the insertion order of the elements

Guess you like

Origin blog.csdn.net/qq_37629227/article/details/112777811