Interview Essentials-Java Collection Framework

Java collection framework interview questions

Common collection

A collection can be seen as a container for storing object information.
The difference between array and collection:
(1) The length of the array cannot be changed and the data with the mapping relationship cannot be saved; the collection class is used to save the data with an uncertain amount and the data with the mapping relationship.
(2) Array elements can be values ​​of basic types or objects; collections can only hold objects.
The Java collection class mainly consists of two interfaces Collection and Map.
Common collections derived from the Collection interface are:

  • (主要)ArrayList、LinkedList
  • (Minor)
    Common collections derived from HashSet, TreeSet, Vector (past tense) Map interface are:
  • (Main) HashMap
  • (Secondary) TreeMap

Briefly explain the difference between List, Set, and Map
List collection: ordered, repeatable collection, each element in the collection has its corresponding sequential index.
The main collections that implement the List interface are: ArrayList, LinkedList, and Vector.

Set collection: ordered, non-repeatable collection, repeated elements will be overwritten.
The main collections that implement the Set interface are: HashSet and TreeSet.

Map collection: Stored in the form of key-value pairs, elements are not stored in order, elements cannot be repeated, repeated elements will be overwritten, key and value can be null
. The collections that implement the Map interface are mainly: HashMap, HashTable, and TreeMap.

(1) ArrayList
ArrayList is a dynamic array, also our most commonly used collection, and is a typical implementation of the List class. It allows any element that conforms to the rules to be inserted even including null. Each ArrayList has an initial capacity of 10, which represents the size of the array. As the elements in the container continue to increase, the size of the container also increases. Each time an element is added to the container, a capacity check will be performed. When it is about to overflow, an expansion operation will be performed. Therefore, if we know how many elements are inserted, it is best to specify an initial capacity value to avoid excessive expansion operations and waste time and efficiency.

(2) LinkedList
LinkedList is another implementation of the List interface. In addition to accessing collection elements based on index, LinkedList also implements the Deque interface, which can be used as a double-ended queue, that is, it can be used as a "stack" , And can be used as a queue.

(3) Vector
is similar to ArrayList, but Vector is synchronous. So Vector is a thread-safe dynamic array. Its operation is almost the same as ArrayList.

(4) HashSet
HashSet cannot guarantee the order of the elements, and is not a collection of thread synchronization. If the HashSet collection is operated by multiple threads, the code should be used to ensure its synchronization. The collection element value can be null

(5) TreeSet
TreeSet can ensure that the elements are in a sorted state, and it uses a red-black tree data structure to store set elements. TreeSet supports two sorting methods: natural sorting and custom sorting. Natural sorting is used by default.

(6) HashMap
HashMap is based on the principle of hashing, storing and obtaining objects through the put() and get() methods. When we pass the key-value pair to the put() method, it calls the hashCode() method of the object to calculate the hashCode value, and then finds the bucket location to store the value object. When obtaining an object, find the correct key-value pair through the equals() method of building the object, and then return the object. HashMap uses a linked list to solve the collision problem. When a collision occurs, the object will be stored in the next node of the linked list.

(7)
The relationship between HashTable and HashMap is completely similar to ArrayList and Vertor. HashMap is not thread-safe, while HashTable is thread-safe. HashMap can use null value as key or value; Hashtable does not allow null value as key and value. When null is put into HashTable, a null pointer exception will occur.

(8) TreeMap is
a red-black tree data structure, and each key-value pair is used as a node of the red-black tree. When TreeMap stores key-value pairs, nodes need to be sorted according to keys.

Frequently Asked Interviews

1. The difference between ArrayList and Vector.

Vector: Thread-safe, data growth is 2 times.
ArrayList: Non-thread safe, data growth is not clearly specified, but from the source code, it is 1.5 times the original growth.

2. The difference between HashMap and HashTable.
  • Different thread safety: HashMap is not thread safe, HashTable is thread safe
  • The inherited parent class is different: Hashtable inherits from Dictionary class, while HashMap inherits from AbstractMap class. But both implement the Map interface.
  • Whether key and value allow null values: In Hashtable, neither key nor value are allowed to appear null values
  • The internal implementation of the two traversal methods is different: link: Map collection traversal
3. Storage performance and characteristics of ArrayList, Vector, LinkedList.

Both ArrayList and Vector use arrays to store data. The number of elements in this array is greater than the actual stored data in order to add and insert elements. They both allow direct indexing of elements by sequence number, but inserting elements involves memory operations such as array element movement, so index data Fast and slow to insert data. Vector uses the synchronized method for thread safety, and its performance is worse than ArrayList.
LinkedList uses a doubly linked list to achieve storage. Indexing data by sequence number requires forward or backward traversal, so indexing data is slower, but when inserting data, you only need to record the preceding and following items of this item, so the insertion speed is faster.

4. The data structure of HashMap.

jdk1.7: Hashmap is actually a hash table of an array and a linked list
jdk1.8: When there are more than 8 elements in the linked list, the linked list will be converted to a red-black tree

5. What is the working principle of HashMap?

Store elements in the form of key-value pairs. HashMap requires a hash function, which uses hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, HashMap will calculate the hash value of the key, and then store the key-value pair in the appropriate index in the collection. If the key already exists, the value will be updated to the new value. Some important characteristics of HashMap are its capacity (capacity), load factor (loadfactor) and expansion limit (threshold resizing)

6. When will HashMap expand?

When the number of elements in the hashmap exceeds the array size loadFactor (load factor), the array will be expanded. The default value of loadFactor is 0.75.

7. What are the characteristics of the three interfaces of List, Map, and Set when accessing elements?

List and Set have similarities. They are both a collection of single-column elements.
Map is different from List and Set. It is a double-column collection.
List represents a sequential collection.
Set cannot have repeated elements.
Map stores key-value values, and values ​​can be multiple values.

8. The elements in the Set cannot be repeated, so what method is used to distinguish whether they are repeated or not? Is == or equals()? What is the difference between them?

The elements in the Set cannot be repeated. Whether the elements are repeated or not is judged by the equals() method. The equals() and == methods determine whether the reference value points to the same object equals() is overridden in the class, in order to return the true value when the content and type of the two separate objects match.

9. Two objects have the same value (x.equals(y)==true), but they can have different hashcodes. Is this sentence correct?

Yes, if objects are to be stored in HashSet or HashMap and their equals are equal, then their hashcode values ​​must be equal. If it is not to be stored in HashSet or HashMap, it has nothing to do with hashcode. At this time, it is okay for hashcode to be different. For example, objects stored in arrayList do not need to implement hashcode. Of course, we have no reason not to implement it. We usually do it.

10. What are the basic interfaces of the Java collection framework?

Collection: Represents a group of objects, each object is its child element.
Set: A Collection that does not contain repeated elements.
List: An ordered collection, and can contain repeated elements.
Map: An object that can map a key to a value, and the key cannot be repeated.

11. What is the underlying implementation of HashSet?

By looking at the source code, we know that the implementation of HashSet relies on HashMap, and the value of HashSet is stored in HashMap. In the construction of HashSet, a HashMap object is initialized. HashSet does not allow repeated values. Therefore, the value of HashSet is stored in the HashMap as the key of the HashMap, and false is returned when the stored value already exists.

12. What is the difference between HashSet and TreeSet?

HashSet is implemented by a hash table, therefore, its elements are unordered. add(), remove(), contains() TreeSet is implemented by a tree structure, the elements in it are ordered. Therefore, the time complexity of add(), remove(), contains() methods is O(logn)

13. Why does the collection class not implement the Cloneable and Serializable interfaces?

The semantics and meaning of cloning or serialization are related to specific implementations. Therefore, the specific implementation of the collection class should decide how to be cloned or serialized.

14. What is the difference between Array and ArrayList? When should I use Array instead of ArrayList?

Array can contain basic types and object types, and ArrayList can only contain object types. The size of Array is fixed, and the size of ArrayList changes dynamically. When ArrayList deals with fixed-size basic data types, this method is relatively slow.

15. The difference between Collection and Collections.

Collection is the superior interface of the collection class, and the inheritance and its interfaces are mainly set and list. The collections class is a helper class for the collection class. It provides a series of static methods for searching, sorting, thread safety and other operations on various collections.

16. What are the Comparable and Comparator interfaces? List their differences.

Java provides a Comparable interface that contains only a compareTo() method. This method can sort two objects individually. Specifically, it returns negative numbers, 0, and positive numbers to indicate that the input object is less than, equal to, or greater than an existing object.
Java provides a Compare() and equals() Comparator interface. The compare() method is used to sort the two input parameters, returning a negative number, 0, and a positive number indicating that the first parameter is less than, equal to, or greater than the second parameter. The equals() method requires an object as a parameter, which is used to determine whether the input parameter is equal to the comparator. This method returns true only when the input parameter is also a comparator and the input parameter is the same as the sort result of the current comparator.

Guess you like

Origin blog.csdn.net/weixin_44231137/article/details/109633382