Java Collections Framework interview questions

A common set of

A collection can be thought of as a container for storing object information. The differences between arrays and collections are as follows: (1) Array length is immutable and cannot store mapped data; The collection class is used to hold an indefinite amount of data and to hold data that has a mapping relationship. (2) Array elements can be either primitive values or objects; Collections can only hold objects. Java Collection classes consist mainly of two interfaces: Collection and Map. Common collections derived from the Collection interface are:

  • (main) ArrayList, LinkedList
  • Common collections derived from the Map interface are:
  • (Main) HashMap
  • (Minor) TreeMap

List collection: an ordered, repeatable collection in which each element has a corresponding sequential index. List interface implementation of the main collection: ArrayList, LinkedList, Vector.

Set: Ordered, non-repeatable Set, overwritten by repeating elements. The Set of Set interfaces mainly include: HashSet, TreeSet.

Map set: Stored in key-value pairs, elements are not stored in sequence, elements cannot be repeated, duplicate elements will be overwritten, and the key and value can be null. Sets of Map interfaces mainly include HashMap, HashTable, and TreeMap.

ArrayList is a dynamic array. ArrayList is a typical implementation of the List class. It allows any element that conforms to the rule to be inserted, including NULL. Each ArrayList has an initial capacity of 10, which represents the size of the array. As the number of elements in the container increases, so does the size of the container. A capacity check is performed each time an element is added to the container, and when overflow is imminent, capacity expansion is performed. Therefore, if we know how many elements to insert, it is better to specify an initial capacity value, so as to avoid wasting time and efficiency by too many expansion operations.

LinkedList is another implementation of the List interface. In addition to accessing collection elements by index, LinkedList also implements a Deque interface that can be used as a double-ended queue, that is, as either a stack or a queue.

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

A HashSet is a collection of elements that cannot be kept in order and are not synchronized by threads. If multiple threads operate on a HashSet, they should be synchronized by code. The value of the elements can be null

TreeSet can ensure that elements are in the sorted state. TreeSet uses 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.

HashMap is based on hashing, using the put() and get() methods to store and retrieve objects. When we pass the key-value pair to the put() method, it calls the hashCode() method of the built object to compute the hashCode value and then finds the bucket location to store the value object. When an object is fetched, it finds the correct key-value pair by setting up its equals() method and then returns the object. A HashMap uses a linked list to solve collisions, and when a collision occurs, the object is stored in the next node in the list.

(7) The relationship between HashTable and HashMap is completely similar to that between ArrayList and Vertor. HashMap is thread-safe and HashTable is thread-safe, and HashMap can use null as key or value. Hashtable does not allow null values for keys and values, and null pointer exceptions will occur if null values are placed in Hashtable.

(8) TreeMap Data structure of a red-black tree, where each key-value pair acts as a node of the red-black tree. When TreeMap stores key-value pairs, nodes need to be sorted by key.

The interview often ask

1. The difference between ArrayList and Vector.

Vector: Thread-safe, 2x data growth. ArrayList: non-thread-safe, data growth is undefined, 1.5 times the original growth from the source code.

2. Differences between HashMap and HashTable.
  • Thread-safe differences: HashMap is not thread-safe, HashTable is thread-safe
  • The inherited parent is different: Hashtable inherits from Dictionary classes, while HashMap inherits from AbstractMap classes. But both implement the Map interface.
  • Whether to allow null values for keys and values: In Hashtable, null values are not allowed for keys and values
  • There are internal implementation differences between the two traversal modes
3. The ArrayList, Vector, LinkedList storage performance and features.

ArrayList and Vector both store data in arrays that have more elements than the actual number of stored data to add and insert elements. They both allow elements to be indexed directly by ordinal number. However, inserting elements involves memory operations such as moving array elements, so indexing data is fast and inserting data is slow. Vector performs worse than ArrayList because of its thread-safe use of the synchronized method. However, LinkedList uses bidirectional LinkedList to realize storage. Index data by serial number needs to be traversed forward or backward, so the index data is slow. However, when inserting data, only the items before and after this item need to be recorded, so the insertion speed is fast.

4. Data structure of HashMap.

Jdk1.8: When the list has more than eight elements, the list is converted to a red-black tree

5. How does HashMap work?

Storing elements as key-value pairs. A HashMap requires a hash function that uses the hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, the HashMap computes the hash value of the key and stores the key-value pair on the appropriate index in the collection. If the key already exists, the value will be updated to the new value. Some of the important features of HashMap are capacity, loadfactor, and thresholdresizing.

6. When will HashMap be expanded?

Array expansion occurs when the number of elements in a HashMap exceeds the array size loadFactor, which defaults to 0.75.

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

List and Set are similar in that they are single-column sets. Map, unlike List and Set, is a two-column Set. List means a sequential Set. Set cannot have duplicate elements. Map holds key-values, values can have multiple values

8. Elements in a Set cannot be repeated, so what is the way to tell whether they are repeated or not? Equals == or equals()? What’s the difference?

Elements in a Set cannot be repeated. They are checked using equals(). The equals() and == methods determine whether a reference value refers to the same object. Equals () is overridden in the class so that it returns true if the contents and types of two separate objects match.

9. Two objects with the same value (x.equals(y)==true) can have different hashcodes.

Yes, if objects are to be stored in a HashSet or a HashMap and their equals are equal, then their HashCode values must be equal. If you don’t want to store it in a HashSet or a HashMap, then you don’t need to implement HashCode. For example, you don’t need to implement HashCode for objects stored in an arrayList. Of course, there’s no reason not to implement it.

10. What are the basic interfaces of the Java Collection Class framework?

Collection: Represents a group of objects, each of which is a child element. Set: A Collection that does not contain repeating elements. List: An ordered collection that can contain repeating elements. Map: An object that maps keys to values. Keys cannot be duplicated.

11. What is the underlying implementation of HashSet?

The implementation of a HashSet depends on a HashMap. The values of a HashSet are stored in a HashMap. In the construction of a HashSet, a HashMap object is initialized. A HashSet does not allow duplicate values. Therefore, the value of the 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?

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

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

The semantics and meanings of cloning or serialization are implementation-specific. Therefore, it is up to the implementation of the collection class to decide how it is cloned or serialized.

What’s the difference between an Array and an ArrayList? When should you use Array instead of ArrayList?

Array can contain both primitive and object types, and ArrayList can contain only object types. The Array size is fixed, whereas the size of an ArrayList changes dynamically. This approach is relatively slow when arrayLists deal with basic data types of fixed size.

15. What is the difference between Collection and Collections?

Collection is the parent interface of the collection class. The main interfaces inherited from it are set and List. The Collections class is a helper class for the collections class. It provides a set of static methods for searching, sorting, thread-safe operations on various collections.

16. What are the Comparable and Comparator interfaces for? List the 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 Comparator interface that contains the compare() and equals() methods. The compare() method is used to sort two input arguments, returning a negative number, 0, with a positive number indicating that the first argument is less than, equal to, or greater than the second argument. The equals() method takes an object as a parameter that determines whether the input parameters are equal to the comparator. This method returns true only if the input parameter is a comparator and the sorting result of the input parameter is the same as the current comparator. Conclusion: there is no end to learning. Learning is an attitude. No matter you are a rookie or a technical bull, you can’t fall behind in learning.

! [](https://upload-images.jianshu.io/upload_images/24492102-fca600682b6332b6.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

The above is my experience to share, and information collation, all packaged, are free to share, waiting for you love learning, need these information friends can private message me oh