Java collection framework is the foundation of Java programming language, which is also a very important knowledge point in Java interview. Here, I’ve listed some important questions and answers about Java collections.

1. What is the Java Collections Framework? What are some of the benefits of a collection framework?

Collections are found in every programming language, and the original Java version contained several collection classes: Vector, Stack, HashTable, and Array.

With the widespread use of collections, Java1.2 presents a collection framework that encompasses all collections interfaces, implementations, and algorithms. Java has a long history of using generics and concurrent collection classes in a thread-safe way. It also includes blocking interfaces and their implementations in Java and sending packages.

Some of the benefits of the collection framework are as follows: (1) Using core collection classes to reduce development costs rather than implementing our own collection classes. (2) Code quality improves with the use of rigorously tested collection framework classes. (3) Code maintenance costs can be reduced by using the collection classes shipped with the JDK. (4) Reusability and operability.

2. What are the advantages of generics in the collection framework?

1.Java1.5 introduced generics, which are heavily used by all collection interfaces and implementations. 2. Generics allow us to provide a collection with an object type that can hold, so if you add any elements of other types, it will report an error at compile time. 3. This avoids a ClassCastException at runtime because you will get an error message at compile time. 4. Generics also keep the code clean, so we don’t need to use explicit conversions and instanceOf operators. 5. It also benefits the runtime because no type-checking bytecode instructions are generated.

3. What are the basic interfaces of the Java Collections framework?

Collection is the root interface at the Collection level. A collection represents a set of objects that are its elements. The Java platform does not provide any direct implementation of this interface.

A Set is a collection that cannot contain duplicate elements. This interface models mathematical set abstractions that are used to represent sets, like a deck of cards.

A List is an ordered collection that can contain repeating elements. You can access any element by its index. List is more like an array of dynamically varying lengths.

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

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

4. Why does Collection not inherit from Cloneable and Serializable interfaces?

The Collection interface specifies a set of objects, which are its elements. How these elements are maintained is up to the implementation of the Collection. For example, some Collection implementations, such as List, allow duplicate elements, while others, such as Set, do not.

Many Collection implementations have a public clone method. However, it also doesn’t make sense to put it in all implementations of the collection. This is because Collection is an abstract representation. What matters is implementation.

The semantics and implications of cloning or serialization come into play when dealing with concrete implementations. Therefore, the implementation should decide how it is cloned or serialized, or whether it can be cloned or serialized. Click here to learn how to serialize.

Authorizing cloning and serialization across all implementations ultimately leads to less flexibility and more restrictions. The specific implementation should determine whether it can be cloned and serialized. Click here to learn how to serialize.

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

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

If Map inherits the Collection interface, where do elements go? A Map contains key-value pairs, which provide a way to extract a list of keys or values, but it does not fit the “set of objects” specification.

6. What is Iterator?

The Iterator interface provides an interface to iterate over any Collection. We can get an iterator instance from a Collection using the iterator method. Iterators replace Enumeration in the Java Collections framework. Iterators allow callers to remove elements during iteration.

7. What are the differences between Enumeration and Iterator interfaces?

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

Iterators replace Enumeration in the Java Collections framework. Iterators allow callers to remove elements from a collection, which Enumeration does not. The iterator method name has been improved to make its functionality clearer.

8. Why isn’t there a method like iterator.add () to add elements to the collection?

Iterator’s protocol does not guarantee the order of iterations. Note, however, that ListIterator does not provide an Add operation, which ensures the order of iterations.

9. Why doesn’t an iterator have a way to get the next element directly without moving the cursor?

It can be implemented at the top of the current Iterator, but it’s used so infrequently that if you add it to the interface, it doesn’t make sense for every inheritance to implement it.

10. What is the difference between Iterater and ListIterator?

(1) We can use Iterator to iterate over sets and lists, whereas ListIterator can only iterate over lists. (2) Iterator can traverse only forward, whereas LIstIterator can traverse both ways. (3) ListIterator inherits from the Iterator interface and then adds some additional functionality, such as adding an element, replacing an element, and getting the index position of the preceding or following element.

11. What do you learn from the iterator fail-fast property?

Each time we try to fetch the next element, the Iterator fail-fast property checks for any changes in the current collection structure. If you find any changes, it throw ConcurrentModificationException. All implementations of iterators in the Collection are fail-fast (with the exception of concurrent Collection classes such as ConcurrentHashMap and CopyOnWriteArrayList).

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

The Iterator’s fail-fast property works with the current collection, so it is not affected by any changes in the collection. All the collection classes in the java.util package are designed to be fail-fast, while the collection classes in java.util. Concurrent are fail-safe.

Losing – fast iterator throw ConcurrentModificationException, losing – safe never throw ConcurrentModificationException iterator.

13. How to avoid iterating over a collection?

ConcurrentModificationException? At the time of traverse a collection we can use the concurrent collection classes to avoid ConcurrentModificationException, such as using CopyOnWriteArrayList, rather than the ArrayList.

14. Why is there no implementation of the Iterator interface?

The Iterator interface defines methods for iterating through collections, but its implementation is the responsibility of the collection implementation class. Each collection class that returns an Iterator for traversal has its own Iterator implementation inner class.

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

15. UnsupportedOperationException is what?

UnsupportedOperationException is used to indicate the operation does not support exception. Has been widespread use in the JDK classes, in the Java Collections framework. Util. Collections. UnmodifiableCollection will throw in all the add and remove operations this exception.

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

The HashMap uses the Key object’s hashCode() and equals() methods to determine the index of the key-value pair. Click here to find out how they relate.

These methods are also used when we try to get values from a HashMap. If these methods are not implemented correctly, in which case two different keys might produce the same hashCode() and equals() output, the HashMap will consider them the same and overwrite them instead of storing them in different places.

Similarly, all collection classes that don’t allow duplicate data use hashCode() and equals() to find duplicates, so it’s important to implement them correctly. Implementations 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 o1.equals(o2) will be true.

17. What are the different collection views provided by the Map interface?

The Map interface provides three collection views:

1) Set keySet () : Returns a Set view of all keys contained in the map. Collections are supported by maps, and changes to maps are reflected in collections and vice versa. When an iterator is iterating over a collection, the result of the iterator becomes undefined if the map is modified (except for the iterator’s own removal operation). Remove, set. Remove, removeAll, retainAll, and clear Iterator operations to Remove elements from the map. It does not support add and addAll operations.

2) Collection Values () : Returns a Collection view of all the values contained in a map. This collection is supported by a map, and changes to the map are reflected in the collection and vice versa. When an iterator is iterating over a collection, if the map is modified (except for the iterator’s own removal operation), the result of the iterator becomes undefined. Remove, set. Remove, removeAll, retainAll, and clear Iterator operations to Remove elements 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. This collection is supported by map, and changes to the map are reflected in the Collection and vice versa. When an iterator is iterating over a collection, the result of the iterator becomes undefined if the map is modified (except by removing the iterator itself and setValue on the entry returned by the iterator). Remove, set. Remove, removeAll, retainAll, and clear Iterator operations to Remove elements from the map. It does not support add and addAll operations.

18. What is the difference between HashMap and HashTable?

(1) A HashMap allows keys and values to be null, whereas a HashTable does not. (2) HashTable is synchronous, HashMap is not. So HashMap is good for single-threaded environments, and HashTable is good for multi-threaded environments. (3) in Java1.4, LinkedHashMap, a subclass of HashMap, was introduced. If you want to traverse the order, you can easily switch from HashMap to LinkedHashMap, but not HashTable, which is in an unpredictable order. (4) HashMap provides Set traversal of keys, so it is fail-fast, but HashTable provides Enumeration traversal of keys, and it does not support fail-fast. (5) HashTable is considered a legacy class, and if you seek to modify the Map during iteration, you should use CocurrentHashMap.

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

A HashMap is the best choice for inserting, deleting, and positioning elements into a Map. However, if you need to iterate over an ordered set of keys, TreeMap is a better choice. Depending on the size of your collection, it may be faster to add elements to the HashMap, replacing the map with TreeMap for an ordered key traversal.

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

Arraylists and vectors are very similar in many ways. (1) Both are index-based and internally supported by an array. (2) Both maintain the insertion order, we can obtain elements according to the insertion order. (3) Iterator implementations of ArrayList and Vector are fail-fast. (4) ArrayList and Vector both allow null values, as well as random access to elements using index values. Here are the differences between ArrayList and Vector. (1) Vector is synchronous, ArrayList is not. However, if you are looking to make changes to the list during iteration, you should use CopyOnWriteArrayList. (2) ArrayList is faster than Vector because it is synchronized and does not overload. (3) ArrayList is more general because we can easily get synchronous and read-only lists using the Collections utility class.

21. What’s the difference between Array and ArrayList? When is it better to use Array?

Array can hold primitive types and objects, whereas ArrayList can only hold objects. Array is a specified size, whereas ArrayList is a fixed size. Array doesn’t offer the same functionality as ArrayList, such as addAll, removeAll, and iterator. Although an ArrayList is clearly the better choice, there are times when an Array is better. (1) If the size of the list is specified, it is mostly stored and traversed. (2) For traversing base data types, although Collections uses automatic boxing to ease the coding task, working on a list of base types of a given size can also be slow. (3) If you want to use multidimensional arrays, it is easier to use [][] than List<List<>>.

22. What is the difference between ArrayList and LinkedList?

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

1) ArrayList is an index-based data structure supported by Array, so it provides random access to elements with complexity O(1), but LinkedList stores a series of node data, each connected to the previous and the next node. So, although there are ways to get elements using indexes, the internal implementation starts at the starting point, walks to the indexed node and returns the element in O(n) time, slower than ArrayList.

2) Inserting, adding, and removing an element from LinkedList is faster than ArrayList, because there is no resize of the array or updating the index when an element is inserted into the middle.

3) LinkedList consumes more memory than ArrayList because each node in LinkedList stores references to the nodes before and after.

23. Which collection classes provide random access to elements?

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

24. Which collection classes are thread-safe?

Vector, HashTable, Properties, and Stack are synchronous classes, so they are thread-safe and can be used in multithreaded environments. The Java1.5 concurrency API includes a number of collection classes that allow iterative modification, and because they all work on clones of collections, they are safe in a multithreaded environment. Click here to find out what thread is unsafe.

25. What is a concurrent collection class?

Java1.5 concurrency (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified during iteration. Iterators are designed to fail – fast, will throw ConcurrentModificationException. Some classes are CopyOnWriteArrayList, ConcurrentHashMap, and CopyOnWriteArraySet.

26. What are queues and stacks? List the differences?

Both stacks and queues are used to prestore data. Java.util. Queue is an interface whose implementation class is in Java and sent to a package. Queues allow first-in, first-out (FIFO) retrieval of elements, but not always. The Deque interface allows elements to be retrieved from both ends. 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.

27. What is the Collections class?

Java.util.collections is a utility class that contains only static methods that operate on or return Collections. It contains polymorphic algorithms that operate on sets, returns a new set supported by the specified set, and other things. This class contains methods for the collection framework algorithm, such as half-search, sorting, remix, and reverse ordering.

What are the differences between 28.Comparable and Comparator interfaces?

The Comparable and Comparator interfaces are used to sort collections or arrays of objects. The Comparable interface is used to provide natural ordering of objects, and we can use it to provide ordering based on a single logic. The Comparator interface is used to provide different sorting algorithms, and we can choose which Comparator we want to use to sort a given collection of objects.

29. How do we sort a set of objects?

If we need to sort an array of objects, we can use the arrays.sort () method. If we need to sort a list of objects, we can use collection.sort (). Both classes have an overloaded sort() method for natural sorting (using Comparable) or standards-based sorting (using Comparator). Collections use an array sort approach internally, and all of them have the same performance, except that Collections takes the time to convert lists into arrays.