40 common java development interview questions and answers

Java collection framework is the basis of Java programming language and an important knowledge point in Java interview. Here, I've listed some important questions and answers about Java collections.

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

There are collections in every programming language, and the original java version contained several collection classes: vector, stack, hashtable, and array. With the widespread use of collections, Java 1 2. A collection framework including all collection interfaces, implementations and algorithms is proposed. Java has been using generic and concurrent collection classes to ensure thread safety for a long time. It also includes blocking interfaces and their implementations in Java Concurrent packages. Some of the advantages of the collection framework are as follows:

(1) use core collection classes to reduce development costs, rather than implementing our own collection classes.

(2) with the use of strictly tested collection framework classes, the code quality will be improved.

(3) the code maintenance cost can be reduced by using the set class attached to the JDK.

(4) reusability and operability.

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

  Java1. 5 introduces generics, which are widely used by all collection interfaces and implementations. Generics allow us to provide a collection with an object type that can be accommodated, so if you add any element of other types, it will make an error when compiling. This avoids ClassCastException at runtime, because you will get an error message at compile time. Generics also make the code neat. We don't need to use explicit conversion and instanceof operator. It also benefits the runtime because it does not produce bytecode instructions for type checking.

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

Collection is the root interface of 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.

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

A list is an ordered collection that can contain duplicate elements. You can access any element through its index. List is more like an array with dynamic length transformation.

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

Some other interfaces are queue, dequeue, sortedset, SortedMap, and listiterator.

  4. Why does the collection not inherit from Cloneable and serializable interfaces?

The collection interface specifies a set of objects, which are its elements. How to maintain these elements is determined by the specific 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 makes no sense to put it in all 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 decide how to clone or serialize it, or whether it can be cloned or serialized.

In all implementations, cloning and serialization are authorized, resulting in less flexibility and more restrictions. A particular implementation should determine whether it can be cloned and serialized.

  5. Why does the map interface not inherit the collection interface?

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

If the map inherits the collection interface, where does the element go? Map contains key value pairs. It provides a method to extract key or value list sets, but it is not suitable for & ldquo; A set of objects & rdquo; standard.

  6. What is iterator?

The iterator interface provides an interface to traverse any collection. We can use the iterator method to get the iterator instance from a collection. Iterators replace enumeration in the Java collection framework. Iterators allow callers to remove elements during iterations.

  7. What is the difference between the 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, compared with enumeration, iterator is safer because it prevents other threads from modifying the collection when a collection is being traversed.

Iterators replace enumeration in the Java collection framework. Iterators allow callers to remove elements from the collection, which enumeration cannot. Iterator method names have been improved to make it more functional.

  8. Why not like iterator Add () to add elements to the collection?

The semantics are unknown. It is known that the iterator protocol cannot ensure 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 method 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. If it is added to the interface, each inheritance has to implement it, which is meaningless.

  10. What is the difference between iterator and listiterator?

(1) we can use iterator to traverse set and list sets, 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 then adds some additional functions, such as adding an element, replacing an element, and obtaining the index position of the previous or subsequent elements.

  11. What are the different ways to traverse a list?

List<String> strList = new ArrayList<>();
//使用for-each循环
for(String obj : strList){
  System.out.println(obj);
}
//using iterator
Iterator<String> 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 currently traversed collection element is changed.

  12. What do you understand through the fail fast attribute of the iterator?

Each 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 a concurrentmodificationexception. The implementation of all iterators in the collection is designed according to fail fast (except concurrent collection classes such as concurrenthashmap and copyonwritearraylist).

  13. What is the difference between fail fast and fail safe?

The fail fast attribute of the iterator works with the current collection, so it is not affected by any changes in the collection. Java. All collection classes in the util package are designed to fail fast, while Java util. The collection classes in concurrent are all fail safe. The fail fast iterator throws a concurrentmodificationexception, while the fail safe iterator never throws a concurrentmodificationexception.

  14. How to avoid concurrent modificationexception when iterating over a collection?

When traversing a collection, we can use concurrent collection classes to avoid concurrent modificationexception, such as copyonwritearraylist instead of ArrayList.

  15. Why is there no specific implementation of the iterator interface?

The iterator interface defines the method of traversing a collection, but its implementation is the responsibility of the collection implementation class. Each collection class that can return an 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, while the copyonwritearraylist iterator is fail safe.

  16. What is unsupported operation exception?

Unsupported operationexception is an exception used to indicate that the operation is not supported. It has been widely used in JDK classes 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 is in map Key value pairs are stored in the static inner class implementation of entry. HashMap uses the hash algorithm. In the put and get methods, it uses the hashcode () and equals () methods. When we call the put method by passing a key value pair, HashMap uses key hashcode () and hash algorithm to find the index storing the key value pair. The entry is stored in the LinkedList, so if there is an entry, it uses the equals () method to check whether the passed key already exists. If it exists, it will overwrite the value. If it does not exist, it will create a new entry and save it. When we call the get method by passing the key, it uses hashcode () again to find the index in the array, then uses the equals () method to find the correct entry, and then returns its value. The following picture 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 to multiply the load factor by the capacity. 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. The 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 the data pulled from the database, it is a good practice to initialize the HashMap with the correct capacity and load factor.

  18. How important are the 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 keys may produce the same hashcode () and equals () outputs. 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 very 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 () does not mean 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. However, before using them, we need to consider the following points:

(1) if the class overrides the equals () method, it should also override the hashcode () method.

(2) all instances of the class need to follow the rules related to equals () and hashcode (). Please refer to these rules mentioned earlier.

(3) if a class does not use equals (), you should not use it in hashcode ().

(4) the best practice of user-defined key class is to make it immutable, so that the hashcode () value can be cached and has better performance. Immutable classes can also ensure that hashcode () and equals () will not change in the future, which will solve the problems related to mutability.

For example, I have a class MyKey, which is used in HashMap.

//传递给MyKey的name参数被用于equals()和hashCode()中
MyKey key = new MyKey('Pankaj'); //assume hashCode=1234
myHashMap.put(key, 'Value');
// 以下的代码会改变key的hashCode()和equals()值
key.setName('Amit'); //assume new hashCode=7890
//下面会返回null,因为HashMap会尝试查找存储同样索引的key,而key已被改变了,匹配失败,返回null
myHashMap.get(new MyKey('Pankaj'));

That is why string and integer are widely used as keys of HashMap.

  20. 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. The collection is supported by map, and the changes of map will be reflected in the collection, and vice versa. When an iterator is traversing a set, if the map is modified (except for the removal operation of the iterator itself), the iterator's result will become undefined. The set supports element removal through the iterator's remove, set.remove, removeAll, retainAll and clear operations to remove the corresponding map from the map. It does not support add and addall operations.

(2) collection values(): returns a collection view of all values contained in a map. This collection is supported by map, and the changes of map will be 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 will become undefined. The collection supports element removal through the remove, set.remove, removeAll, retainAll and clear operations of the iterator to remove the corresponding map 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 the changes of map will be reflected in the collection, and vice versa. When an iterator is traversing a collection, If the map is modified (except for the remove operation of the iterator itself and setValue of the entry returned by the iterator), the result of the iterator will become undefined. The collection supports element removal through the remove, set.remove, removeAll, retainAll and clear operations of the iterator to remove the corresponding map from the map. It does not support add and addall operations.

  21. What is the difference between 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 multi-threaded environment.

(3) LinkedHashMap, a subclass of HashMap, is introduced in Java 1.4. If you want to traverse the order, you can easily turn from HashMap to LinkedHashMap, but hashtable is not like this, and its order is unpredictable.

(4) HashMap provides traversal of the key's set, so it is fail fast, but hashtable provides traversal of the key's enumeration, which does not support fail fast.

(5) hashtable is considered a legacy class. If you want to modify the map during iteration, you should use cocurrenthashmap.

  22. How to choose HashMap or treemap?

For operations such as inserting, deleting, and locating elements in a map, HashMap is the best choice. However, if you need to traverse an ordered set of keys, treemap is a better choice. Based on the size of your collection, it may be faster to add elements to the HashMap. Replace the map with a treemap for orderly key traversal.

  23. What are the similarities and differences between ArrayList and vector?

ArrayList and vector are similar in many cases.

(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) the iterator implementations of ArrayList and vector are both fail fast.

(4) both ArrayList and vector allow null values, or random access to elements using index values.

Here are the differences between ArrayList and vector.

(1) vector is synchronous, but ArrayList is not. However, if you want to change the list during iteration, you should use copyonwritearraylist.

(2) ArrayList is faster than vector. Because it has synchronization, it will not be overloaded.

(3) ArrayList is more general, because we can easily obtain synchronous list and read-only list by using collections tool class.

  24. What is the difference between array and ArrayList? When is it better to use array?

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

Array is of specified size, while ArrayList is of fixed size.

Array does not provide as many functions 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, they are stored and traversed in most cases.

(2) for traversing basic data types, although collections uses automatic boxing to reduce the coding task, it will become very slow to work on the list of basic types of a specified size.

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

  25. What is the difference between 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, and each node is connected with the previous and next nodes. Therefore, although there is a method to obtain elements by index, the internal implementation is to traverse from the starting point, traverse to the index node, and then return the elements. The time complexity is O (n), which is slower than ArrayList.

(2) compared with ArrayList, inserting, adding and deleting an element in LinkedList will be faster, because when an element is inserted into the middle, it will 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 of front and rear nodes.

  26. Which collection classes provide random access to elements?

The ArrayList, HashMap, treemap, and hashtable classes provide random access to elements.

  27. What is enumset?

java. util. Enumset is a collection implementation that uses enumeration types. When a collection is created, all elements in the enumeration collection must come from a single specified enumeration type, which can be displayed or implied. Enumset is out of sync and elements with null values are not allowed. It also provides some useful methods, such as copyof (collection C), of (e first, E & hellip; rest) and complementof (enumsets).

  28. 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. The concurrent API includes some collection classes that can be modified during iteration. Because they all work on the clone of the collection, they are safe in a multithreaded environment.

  29. What are concurrent collection classes?

  Java1. 5. Concurrent (Java. Util. Concurrent) contains thread safe collection classes that allow the collection to be modified during iteration. If the iterator is designed to fail fast, it will throw a concurrentmodificationexception. One is classified as copyonwritearraylist, concurrenthashmap and copyonwritearrayset.

  30. What is BlockingQueue?

  Java. util. concurrent. BlockingQueue is a queue. When retrieving or removing an element, it will wait for the queue to become non empty; When an element is added, it waits for free space in the queue. The BlockingQueue interface is a 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 the producer to have available space or the consumer to have available objects, because it is processed in the BlockingQueue implementation class. Java provides the implementation of centralized BlockingQueue, such as arrayblockingqueue, linkedblockingqueue, priorityblockingqueue, synchronous queue, etc.

  31. What are queues and stacks and list their differences?

Both stacks and queues are used to pre store data. java. util. Queue is an interface whose implementation class is in the Java concurrency package. Queues allow first in first out (FIFO) retrieval of elements, but not always. The deque interface allows retrieval of elements from both ends.

The 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.

  32. What is the collections class?

  Java. util. Collections is a tool class that contains only static methods that operate on or return collections. It contains a polymorphic algorithm that operates on a set, returns a new set supported by a specified set, and some other content. This class contains the methods of set framework algorithms, such as half search, sorting, blending, reverse order, etc.

  33. What are the comparable and comparator interfaces?

If we want to use the sorting method of array or collection, we need to implement Java in the custom class and provide a comparable interface. The comparable interface has a CompareTo (t obj) method, which is used by the sorting method. We should rewrite this method if & ldquo; this” When the object is smaller, equal, or larger than the object parameter passed, it returns a negative integer, 0, or positive integer. However, in most practical cases, we want to sort according to different parameters. For example, as a CEO, I want to sort employees based on salary, and an HR wants to sort them based on age. This is the scenario where we need to use the comparator interface, because comparable CompareTo (object o) method implementation can only sort based on one field. We cannot select fields according to the needs of object sorting. The implementation of the compare (object O1, object O2) method of the comparator interface needs to pass two object parameters. If the first parameter is smaller than the second, it returns a negative integer; If the first is equal to the second, return 0; Returns a positive integer if the first is larger than the second.

  34. What is the difference between 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. We can use it to provide sorting based on a single logic.

The comparator interface is used to provide different sorting algorithms. We can select the comparator to be used to sort a given set of objects.

  35. How do we sort a set of objects?

If we need to sort an array of objects, we can use arrays Sort() method. If we need to sort a list of objects, we can use collection Sort() method. Both classes have overloaded methods sort () for natural sorting (using comparable) or standards based sorting (using comparator). Collections uses array sorting internally, all of which have the same performance, except that collections takes time to convert lists into arrays.

  36. When a collection is passed as a parameter to a function, how can we ensure that the function cannot modify it?

Before passing as a parameter, we can use collections The unmodifiablecollection (collection C) method creates a read-only collection, which ensures that any operation that changes the collection throws an unsupported operationexception.

  37. How do we create a synchronized collection from a given collection?

We can use collections Synchronized collection (collection C) gets a synchronized (thread safe) collection based on the specified collection.

  38. What are the general algorithms implemented in the collection 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 lists, but some are available for all types of collections. Some algorithms include sorting, searching, mixing, maximum and minimum.

  39. What is the capital o? A few examples?

Capital o describes the performance of an algorithm in terms of a series of elements in a data structure. The collection class is the actual data structure. We usually use uppercase o to select the collection implementation based on time, memory and performance. For example: Example 1: get (index I) of ArrayList is a constant time operation, which 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 elements to find the required elements.

  40. What are the best practices related to the Java collection framework?

(1) select the correct set type as needed. For example, if the size is specified, we will choose array instead of ArrayList. If we want to traverse a map according to the insertion order, we need to use treemap. If we don't want to repeat, 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) interface based programming, rather than implementation based programming, allows us to easily change the implementation later.

(4) always use type safe generics to avoid ClassCastException at runtime.

(5) using the immutable class provided by JDK as the key of map can avoid implementing hashcode () and equals ().

(6) use the collections tool class as much as possible, or obtain read-only, synchronous or empty collections instead of writing their own implementation. It will provide code reusability and better stability and maintainability.

Original link: 40 Java collections interview questions and answers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>