In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 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 Java interview questions and answers". 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 the Java interview questions and answers are.
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 it throws a ConcurrentModificationException when the collection element that is currently traversed is changed.
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 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 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. The Fail-fast iterator throws ConcurrentModificationException, while the fail-safe iterator never throws ConcurrentModificationException.
14. How to avoid ConcurrentModificationException when iterating over a collection?
When traversing 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. 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.
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 user-defined key class's practice 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 in equals () and hashCode ()
MyKey key = new MyKey ('Pankaj'); / / assume hashCode=1234
MyHashMap.put (key, 'Value')
/ / the following code changes the hashCode () and equals () values of key
Key.setName ('Amit'); / / assume new hashCode=7890
/ / null will be returned below, because HashMap will try to find the key that stores the same index, but key has been changed. If the match fails, null will be returned.
MyHashMap.get (new MyKey ('Pankaj'))
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.
What is the difference between 21.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.
twenty-two。 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 a 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 23.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 24.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 25.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 is 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) it is faster to insert, add, and delete an element in LinkedList than ArrayList, because when an element is inserted in the middle, it does not involve changing the size of 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.
twenty-six。 Which collection classes provide random access to elements?
The ArrayList, HashMap, TreeMap, and HashTable classes provide random access to elements.
What is 27.EnumSet?
Java.util.EnumSet is a collection implementation that uses enumerated types. When the collection is created, all elements in the enumeration collection must come from a single specified enumeration type, either explicit or implicit. EnumSet is out of sync and elements with a value of null are not allowed. It also provides some useful methods, such as copyOf (Collection c), of (E first,E... Rest) and complementOf (EnumSet s).
twenty-eight。 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.
twenty-nine。 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.
What is 30.BlockingQueue?
Java.util.concurrent.BlockingQueue is a queue that waits for the queue to become non-empty when retrieving or removing an element; when an element is added, it waits for free space in the queue. The BlockingQueue interface is part of the Java collection framework and is mainly used to implement the producer-consumer pattern. We don't need to worry about waiting for producers to have free space or consumers to have available objects, because it's all handled in BlockingQueue's implementation class. Java provides implementations of centralized BlockingQueue, such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, and so on.
thirty-one。 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 32.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 interface between 33.Comparable and Comparator?
If we want to use the sorting method of Array or Collection, we need to implement Java to provide Comparable interface in the custom class. The Comparable interface has a compareTo (T OBJ) method, which is used by sorting methods. We should override this method so that if the "this" object is smaller, equal, or larger than the passed object parameter, it returns a negative integer, 0, or positive integer. However, in most practical cases, we want to sort by different parameters. For example, as a CEO, I want to rank employees based on salary, and a HR wants to rank them by age. This is where we need to use the Comparator interface, because the Comparable.compareTo (Object o) method implementation can only sort based on one field, and we cannot select fields according to the needs of object sorting. The implementation of the compare (Object o1, Object O2) method of the Comparator API needs to pass two object parameters. If * parameters are smaller than the second, a negative integer is returned; if * is equal to the second, 0 is returned; if * is larger than the second, a positive integer is returned.
What is the difference between 34.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.
thirty-five。 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-six。 When a collection is passed to a function as an argument, how can you ensure that the function cannot modify it?
Before passing as an argument, we can use the Collections.unmodifiableCollection (Collection c) method to create a read-only collection, which ensures that any operation that changes the collection throws a UnsupportedOperationException.
thirty-seven。 How do we create a collection of synchronized from a given collection?
We can use Collections.synchronizedCollection (Collection c) to get a synchronized (thread-safe) collection based on the specified collection.
thirty-eight。 What are the general algorithms implemented in the set framework?
The Java collection framework provides common algorithm implementations, such as sorting and searching. The Collections class contains these method implementations. Most algorithms operate on List, but some are available for all types of collections. Some algorithms include sorting, searching, mixing, and * minimum values.
thirty-nine。 What is the capital O? How many examples?
The uppercase O describes the performance of an algorithm in terms of a series of elements in the data structure. The Collection class is the actual data structure, and we usually use uppercase O to select the collection implementation based on time, memory, and performance. For example, the get (index I) of the example 1:ArrayList is a constant time operation that does not depend on the number of elements in the list. So its performance is O (1). Example 2: the performance of a linear search for an array or list is O (n), because we need to traverse all the elements to find the elements we need.
forty。 What are the practices related to the Java collection framework?
(1) choose the correct collection type as needed. For example, if the size is specified, we will choose Array instead of ArrayList. If we want to traverse a Map based on the insertion order, we need to use TreeMap. If we don't want to repeat it, we should use Set.
(2) some collection classes allow the initial capacity to be specified, so if we can estimate the number of storage elements, we can use it to avoid re-hashing or resizing.
(3) programming based on the interface, not the implementation, which allows us to easily change the implementation later.
(4) always use type-safe generics to avoid ClassCastException at runtime.
(5) using the immutable classes provided by JDK as the key of Map, you can avoid implementing hashCode () and equals () yourself.
(6) use Collections utility classes whenever possible, or get read-only, synchronized, or empty collections instead of writing your own implementation. It will provide code reusability, which is more stable and maintainable.
Thank you for your reading, the above is the content of "Java collection interview questions and answers". After the study of this article, I believe you have a deeper understanding of what Java collection interview questions and answers 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.