Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions and answers of the Java collection framework

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the interview questions and answers of the Java collection framework". In the daily operation, I believe many people have doubts about the interview questions and answers of the Java collection framework. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the questions of "interview questions and answers of the Java collection framework". Next, please follow the editor to study!

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

There are collections in every programming language, and the original version of Java included several collection classes: Vector, Stack, HashTable, and Array.

With the widespread use of collections, Java1.2 proposes a collection framework that includes all collection interfaces, implementations and algorithms. Java has a long history of using generics and concurrent collection classes while ensuring thread safety. It also includes blocking interfaces and their implementation in Java concurrent packages.

Some of the advantages of the collection framework are as follows:

Use core collection classes to reduce development costs instead of implementing our own collection classes.

With the use of rigorously tested collection framework classes, the code quality is improved.

By using the collection classes that come with JDK, you can reduce the cost of code maintenance.

Reusability and operability.

two。 What are the advantages of generics in the collection framework?

Java1.5 introduces generics, which are heavily used by all collection interfaces and implementations.

Generics allow us to provide an object type that can be accommodated for the collection, so if you add any other type of element, it will make an error in the compilation time.

This avoids ClassCastException at run time, as you will get an error message at compile time.

Generics also make the code neat, and we don't need to use explicit conversions and instanceOf operators.

It also benefits the runtime because bytecode instructions for type checking are not generated.

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

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

Set is a collection that cannot contain repeating elements. This interface models the abstraction of a mathematical set and is used to represent a collection, like a deck of cards.

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

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

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

4. Why doesn't Collection inherit from the Cloneable and Serializable interfaces?

The Collection interface specifies a set of objects, and the objects are its elements. How to maintain these elements is determined by the specific implementation of 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 doesn't make sense to put it in all the implementations of the collection. This is because Collection is an abstract representation. The important thing is to achieve.

The semantics and meaning of cloning or serialization come into play when dealing with concrete implementations. Therefore, the specific implementation should determine how it is cloned or serialized, or whether it can be cloned or serialized. Click here a literature will be serialized.

Authorizing cloning and serialization in all implementations ultimately leads to less flexibility and more restrictions. A specific implementation should determine whether it can be cloned and serialized. Click here a literature will be serialized.

5. Why doesn't the Map interface inherit the Collection interface?

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

If Map inherits the Collection interface, where do the elements go? Map contains key-value pairs, which provide methods for extracting collections of key or value lists, but it is not suitable for the "set of objects" specification.

What is 6.Iterator?

The Iterator interface provides an interface to traverse any Collection. We can use the iterator method from an Collection to get an iterator instance. Iterators replace Enumeration in the Java collection framework. The iterator allows the caller to remove elements during the iteration.

What is the difference between 7.Enumeration and Iterator interfaces?

Enumeration is twice as fast as Iterator and uses less memory. Enumeration is very basic and meets the basic needs. However, Iterator is more secure than Enumeration 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 callers to remove elements from the collection, which Enumeration cannot. To make its functionality clearer, the iterator method name has been improved.

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

The semantics are unclear, and what is known is that 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 the iterator have a way to get the next element directly without moving the cursor?

It can be implemented at the top level of the current Iterator, but it is rarely used, and it doesn't make sense to implement it with every inheritance if you add it to the interface.

What is the difference between 10.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 in both directions.

(3) ListIterator inherits from the Iterator interface and adds some additional functionality, such as adding an element, replacing an element, and getting the index position of the preceding or subsequent elements.

11. What do you understand through the iterator fail-fast property?

Every time we try to get the next element, the Iterator fail-fast attribute checks for any changes in the current collection structure. If it finds any changes, it throws a ConcurrentModificationException. All Iterator implementations in Collection are designed as fail-fast (except for concurrent collection classes such as ConcurrentHashMap and CopyOnWriteArrayList).

What's the difference between 12.fail-fast and fail-safe?

The fail-fast property of Iterator works with the current collection, so it is not affected by any changes in the collection. All collection classes in the Java.util package are designed to be fail-fast

The collection classes in java.util.concurrent are all fail-safe.

Fall-fast iterator throws ConcurrentModificationException

The fall-safe iterator never throws ConcurrentModificationException.

13. How to avoid iterating over a collection?

ConcurrentModificationException?

We can use concurrent collection classes to avoid ConcurrentModificationException when traversing a collection, such as using CopyOnWriteArrayList instead of ArrayList.

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

The Iterator interface defines a method to traverse the collection, but its implementation is the responsibility of the collection implementation class. Each collection class that can return 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, the ArrayList iterator is fail-fast and the CopyOnWriteArrayList iterator is fail-safe.

What is 15.UnsupportedOperationException?

UnsupportedOperationException is used to indicate that the operation does not support an exception. It has been widely used in the JDK class, and in the collection framework java.util.Collections.UnmodifiableCollection will throw this exception in all add and remove operations.

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

HashMap uses the hashCode () and equals () methods of the Key object to determine the index of the key-value pair. Click here to understand the relationship between them.

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

Similarly, all collection classes that are not allowed to store duplicate data use hashCode () and equals () to find duplicates, so it is important to implement them correctly. The implementation of equals () and hashCode () should follow the following rules:

If o1.equals (O2), then o1.hashCode () = = o2.hashCode () is always true.

If o1.hashCode () = o2.hashCode (), it doesn't mean that o1.equals (O2) will be true.

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

The Map interface provides three collection views:

1) Set keyset (): returns a Set view of all the key contained in the map. Collections are supported by map, and changes in map are 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 becomes undefined. The collection supports element removal and corresponding mapping removal from the map through Iterator's Remove, Set.remove, removeAll, retainAll, and clear operations.

It does not support add and addAll operations.

2) Collection values (): returns a Collection view of all the value contained in a map. This collection is supported by map, and changes in map are reflected in 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 becomes undefined. The collection supports element removal and corresponding mapping removal from the map through Iterator's Remove, Set.remove, removeAll, retainAll, and clear operations. It does not support add and addAll operations.

3) Set entrySet (): returns a collection view of all the mappings contained in a map clock. This collection is supported by map, and changes in map are reflected in 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 becomes undefined. The collection supports element removal and corresponding mapping removal from the map through Iterator's Remove, Set.remove, removeAll, retainAll, and clear operations. It does not support add and addAll operations.

What is the difference between 18.HashMap and HashTable?

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

(2) HashTable is synchronous, but HashMap is not. Therefore, HashMap is suitable for single-threaded environment and HashTable is suitable for multithreaded environment.

(3) A subclass of LinkedHashMap,HashMap is introduced in Java1.4. If you want to traverse the order, you can easily change from HashMap to LinkedHashMap, but HashTable is not like this, and its order is unpredictable.

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

(5) HashTable is considered to be a legacy class, and if you seek to modify Map during iteration, you should use CocurrentHashMap.

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

HashMap is the * * choice for operations such as inserting, deleting, and locating elements in Map. However, if you need to traverse an ordered key collection, TreeMap is the better choice. Depending on the size of your collection, it may be faster to add elements to HashMap, and replace map with TreeMap for orderly key traversal.

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

ArrayList and Vector are very similar in many cases.

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

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

(3) the iterator implementation of ArrayList and Vector is fail-fast.

(4) both ArrayList and Vector allow null values, or you can use index values to randomly access elements.

Here 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 during iterations, you should use CopyOnWriteArrayList.

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

(3) ArrayList is more generic because we can easily get synchronized lists and read-only lists using the Collections utility class.

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

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

The Array is the specified size, while the ArrayList size is fixed.

Array does not provide as many features 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 autoboxing to ease coding tasks, it can be slow to work on lists of primitive types of specified size.

(3) if you want to use multidimensional arrays, it is easier to use [] than List.

What is the difference between 22.ArrayList and LinkedList?

Both ArrayList and LinkedList 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 a complexity of O (1), but LinkedList stores a series of node data, each node connected to the previous and next nodes. So, although there is a way to get an element using an index, the internal implementation is to traverse from the starting point, traverse to the node of the index, and then return the element, with a time complexity of O (n), which is slower than ArrayList.

2) inserting, adding, and deleting an element in LinkedList is faster than ArrayList, because when an element is inserted in the middle, it does not involve resizing the array or updating the index.

3) LinkedList consumes more memory than ArrayList because each node in LinkedList stores references to front and back nodes.

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 a multithreaded environment. Java1.5 concurrent API includes collection classes that allow modification during iteration, because they all work on clones of the collection, so they are safe in a multithreaded environment. Click here to find out why the thread is not safe.

25. What is a concurrent collection class?

The Java1.5 concurrent package (java.util.concurrent) contains thread-safe collection classes that allow the collection to be modified during iteration. The iterator is designed to be fail-fast and throws a ConcurrentModificationException. One is classified as CopyOnWriteArrayList, ConcurrentHashMap and CopyOnWriteArraySet.

twenty-six。 What are queues and stacks and list their differences?

Both the stack and the queue are used to pre-store data. Java.util.Queue is an interface, and its implementation class is in the Java concurrent package. Queues allow FIFO to retrieve elements, but this is not always the case. The Deque interface allows you to retrieve elements from both sides. 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, while Queue is an interface.

What is the 27.Collections class?

Java.util.Collections is a utility class that contains only static methods that manipulate or return collections.

It contains polymorphic algorithms for manipulating sets and returns a new collection and other content supported by the specified set. This class contains methods for set framework algorithms, such as half search, sorting, mixing, and reverse.

What is the difference 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 sorting of objects, and we can use it to provide sorting based on a single logic.

The Comparator interface is used to provide different sorting algorithms, and we can choose which Comparator to use to sort a given set of objects.

twenty-nine。 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 the Collection.sort () method.

Both classes have an overloaded method sort () for natural sorting (using Comparable) or standards-based sorting (using Comparator). Collections uses array sorting internally, and both of them have the same performance, except that Collections takes time to convert lists to arrays.

thirty。 When a collection is passed to a function as an argument, how can you ensure that the function cannot modify it?

Before passing as a parameter, we can use the Collections.unmodifiableCollection (Collection c) method to create a read-only collection

This ensures that any operation that changes the collection throws a UnsupportedOperationException.

At this point, the study of "what are the interview questions and answers of the Java collection framework" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report