Java collection interview questions, are you sure you can pass it?

Just the interview questions compiled yesterday, " The latest compilation of Java interview questions in 2020 " happened to be seen by my colleague, and the following dialogue occurred

同事小鸭

Uh, Timo, there are a lot of these contents on the Internet, so why do you organize them here?

You still take the time to do it. If you have this time, do you read two more books and he doesn't smell it?

帅B提莫

No, it’s simple and convenient for others and yourself(可惜,当时小姐姐没在旁边,不然肯定被我征服了)

Alright, ~ let's continue to update the interview questions!

1. What is the Java Collection Framework? Name some advantages of the collection framework?

There are collections in every programming language. The original Java version contains several collection classes: Vector, Stack, HashTable and Array. With the widespread use of collections, Java 1.2 proposes a collection framework that encompasses all collection interfaces, implementations and algorithms. Java has been experienced for a long time in the use of generics and concurrent collection classes while ensuring thread safety. It is also included in the Java concurrency package, blocking interfaces and their implementation.

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) With the use of rigorously tested collection framework classes, the code quality will be improved.

(3) By using the collection classes included with the JDK, you can reduce code maintenance costs.

(4) Reusability and operability.

** 2. What are the basic interfaces of the Java Collection Framework?

Collection is the root interface of the collection level. A collection represents a group of objects, and these objects are its elements. The Java platform does not provide any direct implementation of this interface.

Set is a collection that cannot contain repeated elements. This interface abstracts a mathematical set and is used to represent the set, just like a deck of cards.

List is an ordered collection that can contain repeated elements. You can access any element by its index. List is more like an array whose length changes dynamically.

Map is an object that maps keys to values. A Map cannot contain duplicate keys: each key can only map one value.

Some other interfaces are Queue, Dequeue, SortedSet, SortedMap and ListIterator.

3. Why does the Map interface not inherit the Collection interface?

Although the Map interface and its implementation are also part of the collection framework, Map is not a collection, and a collection is not a Map either. Therefore, it makes no sense for Map to inherit from Collection and vice versa.

If Map inherits the Collection interface, where do the elements go? Map contains key-value pairs. It provides a method to extract a set of key or value lists, but it is not suitable for the "set of objects" specification.

4. The difference between Enumeration and Iterator interface?

Enumeration is twice as fast as Iterator and also uses less memory. Enumeration is very basic and also meets the basic needs. However, compared with Enumeration, Iterator is safer, because when a collection is being traversed, it prevents other threads from modifying the collection.

Iterators replace Enumeration in the Java collection framework. Iterators allow the caller to remove elements from the collection, which Enumeration cannot do. In order to make its function more clear, the iterator method name has been improved.

5. What is the difference between Iterater 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 an element, and obtaining the index position of the preceding or following element.

6. What are the different ways to traverse a List?

List strList = new ArrayList<>(); 
/*使用for-each循环for(String obj : strList){
    System.out.println(obj);
    }*/ //using iterator
Iterator it = strList.iterator();while(it.hasNext()){
    
    
    String obj = it.next();
    System.out.println(obj);
}

7. Why is there no specific implementation of the Iterator interface?

The Iterator interface defines methods to traverse the collection, but its implementation is the responsibility of the collection implementation class. Each collection class that can return an Iterator for traversal has its own Iterator implementation inner class.

This allows the collection class to choose whether the iterator is fail-fast or fail-safe. For example, ArrayList iterators are fail-fast, while CopyOnWriteArrayList iterators are fail-safe.

8. How does HashMap work in Java?

HashMap stores key-value pairs in the implementation of the Map.Entry static inner class. HashMap uses a hash algorithm. In the put and get methods, it uses hashCode() and equals() methods. When we call the put method by passing a key-value pair, HashMap uses Key hashCode() and a hash algorithm to find the index where the key-value pair is stored.

Entry is stored in LinkedList, so if there is an entry, it uses the equals() method to check whether the passed key already exists. If it does, it will overwrite the value. If it does not exist, it will create a new entry and save it. When we call the get method by passing the key, it uses hashCode() again to find the index in the array, then uses the equals() method to find the correct Entry, and then returns its value. The picture below explains the details.

Other important issues about HashMap are capacity, load factor and threshold adjustment. The default initial capacity of HashMap is 32, and the load factor is 0.75. The threshold is the load factor multiplied by the capacity. Whenever we try to add an entry, if the size of the map is larger than the threshold, HashMap will re-hash the contents of the map and use a larger capacity. The capacity is always a power of 2, so if you know that you need to store a large number of key-value pairs, such as caching data pulled from the database, it is a good practice to initialize the HashMap with the correct capacity and load factor.

9. What is the importance of hashCode() and equals() methods?

HashMap uses the hashCode() and equals() methods of the Key object to determine the index of the key-value pair. These methods will also be used when we try to get values ​​from HashMap. If these methods are not implemented correctly, in this case, two different keys may produce the same hashCode() and equals() output, HashMap will consider them the same, and then overwrite them instead of putting them Store in a different place. Similarly, all collection classes that do not allow storing duplicate 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.

10. What different collection views does the Map interface provide?

The Map interface provides three collection views:

(1) Set keyset(): Returns a Set view of all keys contained in the map. The collection is supported by the map, and the change of the map will be reflected in the collection, and vice versa. When an iterator is traversing a collection, if the map is modified (except for the removal operation of the iterator itself), the result of the iterator will become undefined. The set supports the removal of elements through the Remove, Set.remove, removeAll, retainAll, and clear operations of Iterator to remove the corresponding mapping from the map. It does not support add and addAll operations.

(2) Collection values(): Returns a Collection view of all values ​​contained in a map. If this collection is supported by a map, changes in the map will be reflected in the collection, and vice versa. When an iterator is traversing a collection, if the map is modified (except for the removal operation of the iterator itself), the result of the iterator will become undefined. The set supports the removal of elements through the Remove, Set.remove, removeAll, retainAll, and clear operations of Iterator to remove the corresponding mapping from the map. It does not support add and addAll operations.

(3) Set<Map.Entry<K,V>> entrySet(): Returns a set view of all mappings contained in a map clock. If this collection is supported by map, map changes will be reflected in the collection, and vice versa. When an iterator is traversing a collection, if the map is modified (except for the removal of the iterator itself, and the setValue of the entry returned by the iterator), the result of the iterator will become undefined. The set supports the removal of elements through the Remove, Set.remove, removeAll, retainAll, and clear operations of Iterator to remove the corresponding mapping from the map. It does not support add and addAll operations.

11. What is the difference between HashMap and HashTable?

(1) HashMap allows key and value to be null, while HashTable does not.

(2) HashTable is synchronized, while HashMap is not. So HashMap is suitable for single-threaded environment, HashTable is suitable for multi-threaded environment.

(3) LinkedHashMap, a subclass of HashMap, was introduced in Java 1.4. If you want to traverse the order, you can easily switch from HashMap to LinkedHashMap, but HashTable is not like this, and its order is unpredictable.

(4) HashMap provides traversal of key set, so it is fail-fast, but HashTable provides traversal of key Enumeration, it does not support fail-fast.

(5) HashTable is considered a legacy class. If you seek to modify the Map while iterating, you should use CocurrentHashMap.

12. How to decide whether to use HashMap or TreeMap?

For operations such as inserting, deleting, and positioning 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, it may be faster to add elements to the HashMap. Change the map to a TreeMap to traverse the ordered keys.

13. What are the similarities and differences between ArrayList and Vector?

ArrayList and Vector are similar in many cases.

(1) Both are index-based and are internally supported by an array.

(2) Both maintain the order of insertion, and we can get elements according to the order of insertion.

(3) ArrayList and Vector iterator implementations are fail-fast.

(4) Both ArrayList and Vector allow null values, and you can also use index values ​​for random access to elements.

The following are the differences between ArrayList and Vector.

(1) Vector is synchronous, but ArrayList is not. However, if you seek to make changes to the list while iterating, you should use CopyOnWriteArrayList.

(2) ArrayList is faster than Vector. Because of synchronization, it will not overload.

(3) ArrayList is more versatile, because we can easily obtain synchronized lists and read-only lists using the Collections tool class.

14. What is the difference between Array and ArrayList? When is it better to use Array?

Array can hold basic types and objects, while ArrayList can only hold objects.

Array has a specified size, while ArrayList has a fixed size.

Array does not provide as many functions as ArrayList, such as addAll, removeAll, and iterator. Although ArrayList is obviously a better choice, there are times when Array is easier to use.

(1) If the size of the list has been specified, in most cases it is to store and traverse them.

(2) For traversing basic data types, although Collections uses auto-boxing to ease the coding task, working on a list of basic types with a specified size will also become very slow.

(3) If you want to use a multi-dimensional array, using [][] is easier than List<List<>>.

15. What is the difference between ArrayList and LinkedList?

Both ArrayList and LinkedList implement the List interface, but there are some differences between them.

(1) ArrayList is a data structure based on an index supported by Array, so it provides random access to elements, the complexity is O(1), but LinkedList stores a series of node data, and each node is related to the previous one. Connect to the next node. Therefore, although there are methods to obtain elements using index, the internal implementation is to traverse from the starting point, traverse to the index node and then return the element. The time complexity is O(n), which is slower than ArrayList.

(2) Compared with ArrayList, inserting, adding and deleting an element in LinkedList will be faster, because when an element is inserted in the middle, it will not involve changing the size of the array or updating the index.

(3) LinkedList consumes more memory than ArrayList, because each node in LinkedList stores references to the previous and next nodes.

16. Which collection classes provide random access to elements?

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

17. Which collection classes are thread safe?

Vector, HashTable, Properties, and Stack are synchronous classes, so they are thread-safe and can be used in a multi-threaded environment. The Java1.5 Concurrency API includes some collection classes that allow modification during iteration, because they all work on the clone of the collection, so they are safe in a multithreaded environment.

18. What is a concurrent collection class?

The Java1.5 concurrent package (java.util.concurrent) contains thread-safe collection classes, allowing the collection to be modified during iteration. The iterator is designed to be fail-fast and will throw ConcurrentModificationException. Some of the classes are: CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Well, everyone, today’s interview questions are here first.

If there are any errors in this article, please criticize and advise, I am very grateful!

我是提莫,一个节操泛滥,一身凛然正气,刚正不阿的Java程序员

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/103856445