Interview Questions and answers for 40 Java sets and 40 Java Sets

Source: Internet
Author: User
Tags addall concurrentmodificationexception

Interview Questions and answers for 40 Java sets and 40 Java Sets

Provided by Beijing shangxuetang

1. JavaWhat is a collection framework? What are the advantages of a collection framework?

Each programming language has a set. The original Java version contains several collection classes: Vector, Stack, HashTable, and Array. With the widespread use of collections, Java1.2 proposes a set framework that includes all set interfaces, implementations, and algorithms. Java has been using generic and concurrent collection classes to ensure thread security for a long time. It also includes the blocking interfaces and their implementations in Java concurrent packet sending. The Collection framework has the following advantages:

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

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

(3) use the collection classes attached to JDK to reduce code maintenance costs.

(4) reusability and operability.

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

Java introduces generics, which are widely used by all set interfaces and implementations. Generics allow us to provide a set with an object type that can be accommodated. Therefore, if you add any element of other types, it will return an error during compilation. This avoids ClassCastException during runtime, because you will get an error message during compilation. Generics also make the code clean and tidy. We do not need to use Explicit conversions and instanceOf operators. It also brings benefits to the runtime, because it does not produce bytecode instructions for Type checks.

3. JavaWhat are the basic interfaces of the Collection framework?

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

Set is a Set that cannot contain repeated elements. This interface is used to model mathematical set abstraction, which is used to represent a set, just like a deck.

List is an ordered set that can contain repeated 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 keys to values. A Map cannot contain duplicate keys. Each key can only Map one value at most.

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

4.WhyCollectionNot fromCloneableAndSerializableInterface inheritance?

The Collection interface specifies a group of objects, which are their elements. How to maintain these elements is determined by the specific implementation of Collection. For example, some Collection implementations such as List allow repeated elements, while others such as Set do not. Many collections have a public clone method. However, it is meaningless to put it in all implementations of the set. This is because Collection is an abstract representation. Implementation is important.

When dealing with specific implementations, the semantics and meaning of cloning or serialization play a role. Therefore, the specific implementation should determine how to clone or serialize it, or whether it can be cloned or serialized.

Authorization of cloning and serialization in All implementations leads to less flexibility and more restrictions. The specific implementation should determine whether it can be cloned or serialized.

5.WhyMapInterface does not inheritCollectionInterface?

Although the Map interface and its implementation are also part of the set framework, Map is neither a set nor a set. Therefore, Map inherits the Collection, and vice versa.

If Map inherits the Collection interface, where are the elements? Map contains key-value pairs. It provides a method to extract a set of key or value lists, but it is not suitable for the "one set of objects" Specification.

6. IteratorWhat is it?

The Iterator interface provides an interface for Traversing any Collection. We can use the iterator method in a Collection to obtain the iterator instance. The iterator replaces Enumeration in the Java Collection framework. The iterator allows callers to remove elements during iteration.

7. EnumerationAndIteratorWhat is the difference between interfaces?

Enumeration is twice faster than 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 will prevent other threads from modifying the collection.

The iterator replaces Enumeration in the Java Collection framework. The iterator allows callers to remove elements from the set, but Enumeration cannot. To make its functions clearer, the iterator method name has been improved.

8.Why is there no imageIterator. add ()In this way, add an element to the set?

The semantics is unknown. It is known that the Iterator Protocol cannot ensure the iteration order. However, the ListIterator does not provide an add operation. It must ensure the iteration order.

9.Why does the iterator have no way to directly obtain the next element without moving the cursor?

It can be implemented at the top layer of the current Iterator, but it is rarely used. If you add it to the interface, each inheritance must implement it, which makes no sense.

10. IteraterAndListIteratorWhat is the difference between them?

(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 two 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.TraverseListWhat are the different methods?

1

2

3

4

5

6

7

8

9

10

11

List <String> strList = new ArrayList <> ();

// Use the for-each loop

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 );

}

The iterator is more thread-safe because it ensures that ConcurrentModificationException is thrown when the elements of the current traversal set are changed.

12.Through iteratorFail-fastProperties. What do you understand?

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 change is found, it throws ConcurrentModificationException. All Iterator implementations in Collection are designed based on fail-fast (except ConcurrentHashMap and CopyOnWriteArrayList ).

13. fail-fastAndFail-safeWhat is the difference?

The fail-fast attribute of Iterator works with the current set, so it is not affected by any changes in the set. All the collection classes in the Java. util package are designed as fail-fast, while the 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 iteration of a setConcurrentModificationException?

When traversing a set, we can use the concurrent collection class to avoid ConcurrentModificationException, such as using CopyOnWriteArrayList instead of ArrayList.

15.WhyIteratorDoes the interface have a specific implementation?

The Iterator interface defines the method for traversing the set, but its implementation is the responsibility of the set implementation class. Each collection class that can return Iterator for traversal has its own Iterator implementation internal class.

This allows the collection class to select whether the iterator is fail-fast or fail-safe. For example, the ArrayList iterator is fail-fast, and the CopyOnWriteArrayList iterator is fail-safe.

16. UnsupportedOperationExceptionWhat is it?

UnsupportedOperationException indicates that the operation is not supported. JDK classes are widely used. This exception is thrown in all add and remove operations in the Collection framework java. util. Collections. UnmodifiableCollection.

17.InJavaMedium,HashMapHow does it work?

HashMap stores key-value pairs in the static internal class implementation of Map. Entry. HashMap uses the hash algorithm. In 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 the Key hashCode () and hash algorithm to find the index for storing the key-value pair. The Entry is stored in the exist list. Therefore, if an entry exists, it uses the equals () method to check whether the passed key already exists. If yes, it overwrites the value. If not, it creates a new entry and saves 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 image below explains the details.

Other important problems about HashMap are capacity, load factor, and threshold adjustment. The default initial capacity of HashMap is 32, and the load coefficient is 0.75. The threshold value is multiplied by the load factor by the capacity. whenever we try to add an entry, if the map size is greater than the threshold value, HashMap will re-hash the map content, and use a larger capacity. The capacity is always the power of 2, so if you know that you need to store a large number of key-value pairs, such as the data pulled from the database by the cache, using the correct capacity and load factor to initialize HashMap is a good practice.

18. hashCode ()AndEquals ()How important is the method?

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 correctly implemented, two different keys may generate the same hashCode () and equals () outputs, and HashMap will think they are the same, they are then overwritten, rather than stored in different places. Similarly, all collection classes that do not allow repeated data storage 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), o1.hashCode () = o2.hashCode () is always true.

(2) If o1.hashCode () = o2.hashCode (), it does not mean that o1.equals (o2) will be true.

19.Can we use any classMapOfKey?

We can use any class as the Map key. However, before using them, consider the following:

(1) If the class overrides the equals () method, it should also override the hashCode () method.

(2) All instances of the class must follow the rules related to equals () and hashCode. Refer to the rules mentioned above.

(3) If a class does not use equals (), you should not use it in hashCode.

(4) the best practice of the user-defined key class is to make it immutable. In this way, 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 variable-related problems.

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

1

2

3

4

5

6

7

// 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 the key.

Key. setName ('amit'); // assume new hashCode = 7890

// The following will return null, because HashMap will try to find the key that stores the same index, and the key has been changed. If the matching fails, null is returned.

MyHashMap. get (new MyKey ('pankaj '));

That is why String and Integer are used heavily as HashMap keys.

20. MapWhich different set views does the interface provide?

The Map interface provides three set views:

(1) Set keyset (): returns a Set view of all keys contained in the map. The set is supported by map, and map changes are reflected in the Set, and vice versa. When an iterator is traversing a set, if the map is modified (except for the iterator's own removal operation), The iterator result will become undefined. The collection supports removing elements through the Remove, Set. remove, removeAll, retainAll, and clear operations of Iterator, and removing the corresponding ing from map. It does not support the 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 map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, if the map is modified (except for the iterator's own removal operation), The iterator results will become undefined. The collection supports removing elements through the Remove, Set. remove, removeAll, retainAll, and clear operations of Iterator, and removing the corresponding ing from map. It does not support the add and addAll operations.

(3) Set <Map. Entry <K, V> entrySet (): returns a Set view of all mappings contained in a map clock. This set is supported by map. map changes are reflected in the collection, and vice versa. When an iterator is traversing a set, if the map is modified (except for the iterator's own removal operation and setValue for the entry returned by the iterator ), the result of the iterator changes to undefined. The collection supports removing elements through the Remove, Set. remove, removeAll, retainAll, and clear operations of Iterator, and removing the corresponding ing from map. It does not support the add and addAll operations.

21. HashMapAndHashTableWhat's the difference?

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

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

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

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

(5) HashTable is considered a legacy class. If you want to modify Map during iteration, you should use CocurrentHashMap.

22.How to chooseHashMapOrTreeMap?

HashMap is the best choice for insert, delete, and locate elements in a Map. However, if you need to traverse an ordered key set, TreeMap is a better choice. Based on the size of your collection, it may be faster to add elements to the HashMap. Instead, map is converted into a TreeMap for sequential key traversal.

23. ArrayListAndVectorWhat are the similarities and differences?

ArrayList and Vector are similar in many cases.

(1) Both are based on indexes and are supported by an array internally.

(2) The two maintain the insertion sequence. We can obtain the elements according to the insertion sequence.

(3) The iterator Implementation of ArrayList and Vector is fail-fast.

(4) The ArrayList and Vector values allow null values or random access to Elements Using index values.

The following are differences between ArrayList and Vector.

(1) The Vector is synchronized, but the 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 and will not be overloaded.

(3) ArrayList is more common, because we can use the Collections tool class to easily obtain the synchronization list and read-only list.

24. ArrayAndArrayListWhat is the difference? When is it more suitable?Array?

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

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

Array does not provide the ArrayList functions, such as addAll, removeAll, and iterator. Although ArrayList is obviously a better choice, Array is sometimes easier to use.

(1) If the size of the list has been specified, it is stored and traversed in most cases.

(2) For traversing basic data types, even though Collections uses automatic packing to reduce coding tasks, it will be slow to work on the list of specified basic types.

(3) If you want to use multi-dimensional arrays, it is easier to use [] [] than List <>.

25. ArrayListAndShortlistWhat is the difference?

Both ArrayList and rule List implement the List interface, but there are some differences between them.

(1) ArrayList is an index-based data structure supported by Array. Therefore, ArrayList provides Random Access to elements. The complexity is O (1 ), however, the shortlist stores a series of node data. Each node is connected to the previous node and the next node. Therefore, although an index is used to retrieve elements, 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 ), it is slower than ArrayList.

(2) Compared with ArrayList, It is faster to insert, add, and delete an element in the explain list, because when an element is inserted in the middle, it does not involve changing the array size, or update the index.

(3) The Memory list consumes more memory than the ArrayList, because each node in the memory list stores references of the front and back nodes.

26.Which collection classes provide random access to elements?

The ArrayList, HashMap, TreeMap, and HashTable classes provide random access to elements.

27. EnumSetWhat is it?

Java. util. EnumSet is implemented using a set of enumeration types. When a collection is created, all elements in the enumeration set must come from a single specified enumeration type, which can be displayed or hidden. EnumSet is not synchronized, And the element with a null value is not allowed. It also provides some useful methods, such as copyOf (Collection c), of (E first, E... Rest) and complementOf (EnumSet s ).

28.Which collection classes are thread-safe?

Vector, HashTable, Properties, and Stack are synchronization classes, so they are thread-safe and can be used in multi-threaded environments. Java concurrent APIs include some collection classes that can be modified during iteration. Because they all work on the clone of the set, they are safe in the multi-threaded environment.

29.What is a concurrent collection class?

Java concurrent package (java. util. concurrent) contains the thread security collection class, which allows you to modify the set during iteration. If the iterator is designed as fail-fast, ConcurrentModificationException is thrown. Some classes are: CopyOnWriteArrayList, ConcurrentHashMap, and CopyOnWriteArraySet.

30. BlockingQueueWhat is it?

Java. util. concurrent. blockingQueue is a queue. When an element is retrieved or removed, it waits for the queue to become non-empty. When an element is added, it waits for the available space in the queue. The BlockingQueue interface is part of the Java Collection framework and is mainly used to implement the producer-consumer mode. We do not need to worry about waiting for the producer to have available space or the consumer to have available objects because they are all processed in the BlockingQueue implementation class. Java provides centralized BlockingQueue implementation, such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

31.What are the differences between queues and stacks and listing them?

Both stack and queue are used to pre-store data. Java. util. Queue is an interface, and its implementation class is in Java concurrent package. The queue allows first-in-first-out (FIFO) retrieval elements, but this is not always the case. The Deque interface allows you to retrieve elements from both ends.

The stack is similar to the queue, but it allows you to search for elements in LIFO.

Stack is a class that extends the Vector, while Queue is an interface.

32. CollectionsWhat is a class?

Java. util. Collections is a tool class that only contains static methods, and they operate or return a set. It contains the polymorphism algorithm of the operation set and returns a new set and other content supported by the specified set. This class contains methods of a set framework algorithm, such as semi-search, sorting, mixing, and reverse sorting.

33. ComparableAndComparatorWhat is an interface?

If you want to use the sorting method of Array or Collection, you need to implement the Comparable interface in the Custom class. The Comparable interface has the compareTo (t obj) method, which is used by the sorting method. We should rewrite this method. If the "this" object is smaller, equal, or greater than the passed object parameter, it returns a negative integer, 0, or positive integer. However, in most cases, we want to sort by different parameters. For example, as a CEO, I want to sort employees by salary, and an HR wants to sort them by age. This is the scenario where we need to use the Comparator interface, because the Comparable. compareTo (Object o) method can only sort based on one field, and we cannot select fields based on Object sorting needs. The compare (Object o1, Object o2) method of the Comparator interface must pass two Object parameters. If the first parameter is smaller than the second one, a negative integer is returned. If the first parameter is equal to the second one, returns 0. if the first is greater than the second, a positive integer is returned.

34. ComparableAndComparatorWhat is the difference between interfaces?

The Comparable and Comparator interfaces are used to sort object sets or arrays. The Comparable interface is used to provide the 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 object set.

35.How do we sort a group of objects?

If we need to sort an object array, we can use the Arrays. sort () method. To sort an object list, we can use the Collection. sort () method. Both classes are used for natural sorting (using Comparable) or standard-based sorting (using Comparator) overload Methods sort (). Collections uses the array sorting method internally, all of which have the same performance, but Collections takes time to convert the list to an array.

36.When a set is passed as a parameter to a function, how can we ensure that the function cannot be modified?

Before being passed as a parameter, we can use the Collections. unmodifiableCollection (Collection c) method to create a read-only set, which will ensure that any operation to change the set will throw UnsupportedOperationException.

37.How do we createSynchronized?

We can use Collections. synchronizedCollection (Collection c) to obtain a synchronized (thread-safe) set based on the specified set.

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

The Java Collection framework provides common algorithm implementations, such as sorting and searching. The Collections class contains the implementation of these methods. Most algorithms operate on the List, but some of them are available for all types of sets. Some algorithms include sorting, searching, mixing, and maximum and minimum values.

39.UppercaseOWhat is it? How many examples are there?

In upper case, O describes the performance of an algorithm for a series of elements in the 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 list. So its performance is O (1 ). Example 2: the performance of a linear search for arrays or lists is O (n), because we need to traverse all elements to find the desired elements.

40.AndJavaWhat are the best practices related to the Collection framework?

(1) Select the correct set type as needed. For example, if the size is specified, we use Array instead of ArrayList. If we want to traverse a Map in the insert sequence, we need to use TreeMap. If we do not want to repeat it, we should use Set.

(2) Some collection classes allow you to specify the initial capacity, so if we can estimate the number of storage elements, we can use it to avoid re-hash or size adjustment.

(3) interface-based programming, rather than implementation-based programming, allows us to easily change the implementation later.

(4) type-safe generic is always used to avoid ClassCastException during runtime.

(5) using the unchangeable class provided by JDK as the Map key can avoid self-Implementation of hashCode () and equals ().

(6) use the Collections tool class as much as possible, or obtain a set of read-only, synchronous, or null, rather than writing your own implementations. It will provide code reusability, and it has better stability and maintainability.

 

[For the latest document updates, please join Shang xuexiang www.sxt.cn] [Professional JAVA training institutions, real zero down payment admission www.bjsxt.com]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.