Questions about the Java collection framework (with answers)

  • 2020-04-01 04:30:24
  • OfStack

21. What is the difference between a HashMap and a HashTable?

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

(2) HashTable is synchronous, while HashMap is not. So HashMap works for single-threaded environments, and HashTable works for multi-threaded environments.

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

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

(5) HashTable is considered a legacy class, and if you seek to modify the Map while iterating, you should use CocurrentHashMap.

22. How do you decide whether to use a HashMap or a TreeMap?

HashMap is the best choice for operations like inserting, deleting, and locating elements in a Map. However, if you need to traverse an ordered set of keys, a TreeMap is a better choice. Depending on the size of your collection, it might be faster to add elements to a HashMap, replacing the map with a TreeMap for ordered key traversal.

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

ArrayList and Vector are similar in many ways.

(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, and index values can also be used for random access to elements.

The following are the differences between an ArrayList and a Vector.

(1) Vector is synchronous, while ArrayList is not. However, if you are looking to make changes to the list while iterating, you should use CopyOnWriteArrayList.

(2) ArrayList is faster than Vector, and it will not be overloaded due to synchronization.

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

24. What is the difference between an Array and an ArrayList? When is Array better?

An Array can hold primitive types and objects, while an ArrayList can hold only objects.

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

Array does not provide as much functionality as ArrayList, such as addAll, removeAll, and iterator. While an ArrayList is obviously a better choice, there are times when Array is better.

(1) if the list size is specified, most of the time it is stored and traversed.

(2) for traversing basic data types, even though Collections used autoboxing to ease the coding task, working on a list of basic types of specified size became slow.

(3) if you want to use a multidimensional array, use [][] rather than List< List< > > More easily.

25. What's the difference between an ArrayList and a 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 connected to the previous and next nodes. So, although there is a way to get the elements using the index, the internal implementation iterates from the starting point, traverses to the nodes of the index and then returns the elements, the time complexity is O(n), which is slower than the ArrayList.

(2) it is faster to insert, add, and delete an element in a LinkedList than in an ArrayList, because there is no need to change the size of the array or update the index when an element is inserted in the middle.

(3) LinkedList consumes more memory than ArrayList because each node in the LinkedList stores references to previous and subsequent 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 an EnumSet?

Java.util.enumset is a collection implementation that USES an enumeration type. When a collection is created, all elements in an enumeration collection must come from a single specified enumeration type, which can be either explicit or implicit. Enumsets are out-of-sync and do not allow elements with null values. It also provides some useful methods, such as copyOf(Collection c), of(E first,E... Rest) and complementOf enumsets (s).

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. The Java1.5 concurrent API includes collection classes that are allowed to be modified while iterating, and because they all work on clones of collections, they are safe in a multithreaded environment.

29. What is a concurrent collection class?

The Java1.5 release package (java.util.concurrent) contains a thread-safe collection class that allows the collection to be modified during iteration. Iterators are designed to fail - fast, will throw ConcurrentModificationException. Some of the classes are: CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

30. What is BlockingQueue?

Java. Util. Concurrent. BlockingQueue is a queue, when to retrieve or remove an element, it will wait queue into not empty; When an element is added, it waits for free space in the queue. The BlockingQueue interface is part of the Java collections framework and is primarily used to implement the producer-consumer pattern. We don't have to worry about waiting for producers to have available space, or consumers to have available objects, because it's all being processed in the implementation class of BlockingQueue. Java provides implementations of centralized BlockingQueue, such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, and so on.

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

Both the stack and the queue are used to prestore data. Java.util.Queue is an interface whose implementation class is in the Java and issued package. Queues allow first-in-first-out (FIFO) retrieval of elements, but this is not always the case. The Deque interface allows elements to be retrieved from both ends.

A stack is similar to a queue, but it allows retrieval of elements in a last in, first out (LIFO) manner.

A Stack is a class that extends from a Vector, and a Queue is an interface.

32. 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 a polymorphic algorithm for the set of operations, returns a new set supported by the specified set, and something else. This class contains methods for collection framework algorithms, such as binary search, sort, mix, and reverse.

33. com parable and Comparator interface is what?

If we want to use the Array or Collection sort method, we need to implement Java in our custom class to provide the Comparable interface. The Comparable interface has the compareTo(T OBJ) method, which is used by the sort method. We should override this method to return a negative integer, 0, or positive integer if the "this" object is smaller, equal, or larger than the passed object argument. 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 an HR wants to rank them based on 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 a field based on the sorting of the Object. The implementation of the compare(Object o1, Object o2) method on the Comparator interface needs to pass two Object parameters. If the first parameter is smaller than the second, a negative integer is returned. If the first is equal to the second, return 0; Returns a positive integer if the first is larger than the second.

What's the difference between the 34. com parable and Comparator interface?

The Comparable and Comparator interfaces are used to sort collections of objects or arrays. The Comparable interface is used to provide a natural sort of the object, which we can use to provide a sort 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 set of objects.

35. 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 sort(using Comparable) or standards-based sort(using Comparator). Collections internally use the array sort method, all of which have the same performance, except that Collections take the time to convert the list into an array.

36. When a collection is passed to a function as an argument, how can I be sure that the function cannot modify it?

We can use it before passing it as a parameter The Collections. UnmodifiableCollection (Collection c) Method to create a read-only collection, this will ensure that any operation change collection will throw an UnsupportedOperationException.

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

We can use the Collections. SynchronizedCollection (Collection c) according to the specified set to obtain a synchronized (thread safe).

38. What are the general algorithms implemented in the collection framework?

The Java collections framework provides implementations of commonly used algorithms, 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 are sorting, searching, mixing, maximum and minimum.

39. What is a capital O? How many examples?

Capital O describes the performance of an algorithm in terms of a set of elements in a data structure. The Collection class is the actual data structure, and we typically use capital O to select the Collection implementation based on time, memory, and performance. Example 1: get(index I) of ArrayList is a constant time operation that does not depend on the number of elements in the list. So its performance is order one. 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 required elements.

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

(1) select the right collection type as required. For example, if the size is specified, we would use an Array instead of an ArrayList. If we want to iterate over a Map in insertion order, we need to use a TreeMap. If we don't want to repeat, we should use Set.

(2) some collection classes allow initial capacity to be specified, so if we can estimate the number of stored elements, we can use it without rehashing or resizing.

(3) programming based on interfaces, rather than implementations, allows us to easily change the implementation later.

(4) always use type-safe generics to avoid classcastexceptions at run time.

(5) you can avoid implementing hashCode() and equals() yourself by using the immutable class provided by the JDK as the key of the Map.

(6) use the Collections tool class whenever possible, or get read-only, synchronized, or empty Collections instead of writing your own implementation. It will provide code reuse, it has better stability and maintainability.

The above content is all for the Java collection of questions, think that a good friend decisive collection, you can also combine the last article for learning: (link: #)


Related articles: