In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the interview questions of the JAVA collection?" the content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the interview questions of the JAVA collection.
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:
(1) use core collection classes to reduce development costs instead of implementing our own collection classes.
(2) with the use of strictly tested collection framework classes, the code quality will be improved.
(3) by using the collection classes that come with JDK, the cost of code maintenance can be reduced.
(4) 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. 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.
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 are the different ways to traverse a List? List strList = new ArrayList ()
/ / use for-each loop
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)
}
Using an iterator is more thread-safe because it ensures that when the collection element currently traversed is changed, it throws a
ConcurrentModificationException .
twelve。 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 any changes are found, it throws
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 13.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, while collection classes in java.util.concurrent are fail-safe. Fail-fast iterator throws
ConcurrentModificationException, and the fail-safe iterator never throws
ConcurrentModificationException .
14. How to avoid ConcurrentModificationException when iterating over a collection?
We can use concurrent collection classes to avoid
ConcurrentModificationException, such as using CopyOnWriteArrayList instead of ArrayList.
15. 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 16.UnsupportedOperationException?
UnsupportedOperationException is used to indicate that the operation does not support an exception. Has been widely used in the JDK class, in the collection framework
Java.util.Collections.UnmodifiableCollection will throw this exception in all add and remove operations.
17. How does HashMap work in Java?
HashMap stores key-value pairs in the Map.Entry static inner class implementation. HashMap uses the hash algorithm, and in the put and get methods, it uses the hashCode () and equals () methods. When we call the put method by passing the key-value pair, HashMap uses Key hashCode () and the hash algorithm to find the index that stores the key-value pair. 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 so, it overrides the value, and if not, it creates a new entry and saves it. When we call the get method by passing key, it again uses hashCode () 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, and 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. 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 idea to initialize HashMap with the correct capacity and load factor.
What is the importance of the 18.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 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:
(1) if o1.equals (O2), then o1.hashCode () = = o2.hashCode () is always true.
(2) if o1.hashCode () = o2.hashCode (), it doesn't mean that o1.equals (O2) will be true.
19. Can we use any class as the key of Map?
We can use any class as the key of Map, but before we use them, we need to consider the following:
(1) if the class overrides the equals () method, it should also override the hashCode () method.
All instances of the class need to follow the rules related to equals () and hashCode (). Please refer to these rules mentioned earlier.
If a class does not use equals (), you should not use it in hashCode ().
(4) the best practice for user-defined key classes is to make it immutable so that the hashCode () value can be cached for better performance. Immutable classes can also ensure that hashCode () and equals () will not change in the future, which will solve the problem associated with mutability.
For example, I have a class MyKey that I use in HashMap.
/ / the name parameter passed to MyKey is used for MyKey key = new MyKey ('Pankaj') in equals () and hashCode (); / / assume hashCode=1234myHashMap.put (key,' Value'); / / the following code changes the hashCode () and equals () values of key key.setName ('Amit') Null is returned under / / assume new hashCode=7890//, because HashMap will try to find the key that stores the same index, but key has been changed. If the match fails, nullmyHashMap.get (new MyKey ('Pankaj')) will be returned; that's why String and Integer are widely used as key for HashMap.
What different collection views are provided by the 20.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.
Thank you for your reading, the above is the content of "what are the interview questions of the JAVA collection?" after the study of this article, I believe you have a deeper understanding of what the interview questions of the JAVA collection have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.