Java Aggregate face Test (40-way)

Source: Internet
Author: User
Tags addall serialization concurrentmodificationexception

The Java Collection framework is the foundation of the Java programming language and is an important knowledge point in the Java interview. Here, I have listed some important questions and answers about Java collections. what the 1.Java set frame is. Name some of the advantages of the collection framework.

There are collections in each programming language, and the original Java version contains several collection classes: vectors, Stack, Hashtable, and array. With the extensive use of the set, Java1.2 proposes a set framework encompassing all the set interfaces, implementations, and algorithms. Java has been going on for a long time, using generics and concurrent collection classes while ensuring thread safety. It is also included in Java and the contract, blocking the interface and their implementation. 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 rigorously tested collection framework classes, code quality can be improved.

(3) The cost of code maintenance can be reduced by using the collection classes that are included with the JDK.

(4) reusability and operability. 2. What are the advantages of generics in a collection framework?

Java1.5 introduces generics, and all the collection interfaces and implementations use it heavily. 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 be wrong in the compile times. This avoids classcastexception at run time, because 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 byte code directives that do not produce type checks are generated. what are the base interfaces for the 3.Java collection framework?

Collection is the root interface of the collection hierarchy. A collection represents a set of objects, which are the elements of that object. The Java platform does not provide any direct implementation of this interface.

A set is a collection that cannot contain duplicate elements. This interface models mathematical set abstraction, which is used to represent a collection, 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. The list is more like an array of length dynamic transformations.

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

Some of the other interfaces are queue, dequeue, SortedSet, SortedMap, and Listiterator. 4. Why collection does not inherit from the cloneable and serializable interfaces.

The collection interface specifies a set of objects, the object being 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 are not allowed. Many collection implementations have a publicly-available clone method. However, it is meaningless to put it in all the implementations of the collection. This is because collection is an abstract expression. It is important to achieve.

When dealing with a specific implementation, the semantics and meaning of cloning or serialization play a role. Therefore, a specific implementation should determine how to clone or serialize it, 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 the map interface does not inherit the collection interface.

Although the map interface and its implementation are also part of the collection framework, the map is not a collection and the collection is not a map. Therefore, the map inheritance collection meaningless, and vice versa.

If the map inherits the collection interface, then where does the element go? The map contains a Key-value pair that provides methods for extracting a key or a list of value lists, but it does not fit the "set of objects" specification. 6.Iterator is what.

The iterator interface provides an interface that traverses any collection. We can use an iterator method from a collection to get an iterator instance. The iterator replaces the enumeration in the Java collection framework. An iterator allows the caller to remove elements during an iterative process. the difference between 7.Enumeration and iterator interfaces.

Enumeration is twice times faster than iterator and uses less memory. Enumeration is very basic and meets the needs of the foundation. However, iterator is more secure than enumeration, because when a collection is being traversed, it prevents other threads from modifying the collection.

The iterator replaces the enumeration in the Java collection framework. Iterators allow the caller to remove elements from the collection, and enumeration cannot do so. To make the function clearer, the iterator method name has been improved. 8. Why not add elements to the collection, such as the Iterator.add () method.

The semantics are unknown, and it is known that iterator protocols do not ensure the order of iterations. Note, however, that Listiterator does not provide an add operation to ensure the order of iterations. 9. Why does the iterator not 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 add it to the interface and each inheritance has to implement it. What is the difference between 10.Iterater and listiterator?

(1) We can use iterator to traverse the set and list collection, while Listiterator can only traverse the list.

(2) Iterator can only be traversed forward, while listiterator can be traversed bidirectional.

(3) Listiterator inherits from the iterator interface, and then adds some additional features, such as adding an element, replacing an element, getting the index position of the front or back element. 11. What are the different ways to traverse a list?

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

Using iterators is more thread-safe because it ensures that when the current traversal of the collection element is changed, it throws a concurrentmodificationexception. 12. Through the iterator Fail-fast properties, you understand what.

Every time we try to get the next element, the iterator Fail-fast property checks for any changes in the current collection structure. If any changes are found, it throws a concurrentmodificationexception. All iterator implementations in collection are designed by Fail-fast (except for concurrent collection classes such as Concurrenthashmap and Copyonwritearraylist). What is the difference between 13.fail-fast and fail-safe.

Iterator's Fail-fast properties work 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, and the collection classes in Java.util.concurrent are fail-safe. Fail-fast iterators throw concurrentmodificationexception, while fail-safe iterators never throw 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 the iterator interface does not have a specific implementation.

The iterator interface defines a method of traversing a 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. 16.UnsupportedOperationException is what.

Unsupportedoperationexception is used to indicate an exception that is not supported by the operation. has been used heavily in JDK classes, the exception will be thrown in all add and remove operations in the collection framework java.util.Collections.UnmodifiableCollection. 17. In Java, how HashMap works.

HashMap stores Key-value pairs in the Map.entry static inner class implementation. HashMap uses the hash algorithm, which uses the Hashcode () and the Equals () method in the put and get methods. When we call the Put method by passing Key-value, HashMap uses the 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 a entry, it uses the Equals () method to check if the passed key already exists, and if it does, it overwrites value, and if it does not, it creates a new entry and then saves it. When we call the Get method by passing key, it uses hashcode () again to locate 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 issues that are more important to hashmap are capacity, load factor and threshold adjustment. HashMap The default initial capacity is 32, and the load factor is 0.75. The threshold is multiplied by the capacity of the load factor, and whenever we try to add a entry, if the map size is larger than the valve value, HashMap hashes the contents of the map and uses greater capacity. Capacity is always 2 power, so if you know you need to store a lot of key-value, such as caching data from the database, it's a good idea to initialize HashMap with the right 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 the value from the HashMap. If these methods are not implemented correctly, in this case, two different keys may produce the same hashcode () and Equals () outputs, and HashMap will assume that they are the same and then overwrite them rather than storing them in different places. Similarly, all collection classes that do not allow storing duplicate data use Hashcode () and Equals () to find duplicates, so it is important to implement them correctly. Implementations of Equals () and hashcode () should follow these rules:

(1) if O1.equals (O2), then 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 class as the key of the map.

We can use any class as the key of the map, but before we use 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 associated with equals () and hashcode (). Please refer to the rules mentioned earlier.

(3) If a class does not use Equals (), you should not use it in Hashcode ().

(4) The best practice for user-defined key classes is to make them immutable so that the hashcode () value can be cached for better performance. Immutable classes can also ensure that hashcode () and Equals () do not change in the future, thus resolving variable-related problems.

For example, I have a class mykey that uses it 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 key's Hashcode () and Equals () value
key.setname (' Amit '), and//assume new hashcode=7890
//below returns NULL. Because HashMap will try to find the key that stores the same index, the key has been changed, the match fails, and the null
myhashmap.get (the ' Pankaj ') is returned.

That is why string and integer are used heavily as HashMap key. 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 key contained in the map. The collection is supported by the map, and the changes in the 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 of the iterator itself), the result of the iterator becomes undefined. The collection supports the removal of elements through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations and removes the corresponding mappings from the map. 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 the map, and changes in the 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 of the iterator itself), the result of the iterator becomes undefined. The collection supports the removal of elements through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations and removes the corresponding mappings from the map. It does not support add and addall operations.

(3) set<map.entry<k,v>> EntrySet (): Returns a collection view of all mappings contained in a map clock. This collection is supported by the map, which is reflected in the collection and vice versa. When an iterator is traversing a collection, if the map is modified (except for the entry of the iterator itself and the SetValue returned by the iterator), the result of the iterator becomes undefined. The collection supports the removal of elements through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations and removes the corresponding mappings from the map. 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, while Hashtable is not allowed.

(2) Hashtable is synchronous, and HashMap is not. So HashMap is suitable for single-threaded environment, Hashtable is suitable for multi-threaded environment.

(3) A subclass of Linkedhashmap,hashmap is introduced into the Java1.4, and 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 a set for the key to traverse, so it is fail-fast, but Hashtable provides the enumeration of the key to traverse, it does not support fail-fast.

(5) Hashtable is considered a legacy class, and if you seek to modify the map at iteration time, you should use Cocurrenthashmap. 22. How to decide 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 key set, TreeMap is a better choice. Based on the size of your collection, it may be quicker to add elements to the HashMap, and change the map to TreeMap for an ordered key traversal. what are the similarities and differences between 23.ArrayList and vector?

ArrayList and vectors are very similar in many cases.

(1) Both are indexed and internally supported by an array.

(2) Both maintain the insertion order, and we can get the elements according to the order of insertion.

(3) The implementation of ArrayList and Vector iterators is fail-fast.

(4) Both ArrayList and vectors allow null values, or you can use index values to randomly access elements.

The following are the differences between ArrayList and vectors.

(1) vector is synchronous, and ArrayList is not. However, if you are looking for a change to the list at the time of the iteration, you should use Copyonwritearraylist.

(2) ArrayList is faster than vector, because it is synchronized, it will not overload.

(3) ArrayList is more versatile because we can easily get synchronized lists and read-only lists using the Collections tool class. What is the difference between 24.Array and ArrayList? When is the best time to use array.

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

The array is of the specified size, and the ArrayList size is fixed.

Array does not provide ArrayList so many functions, such as AddAll, RemoveAll and iterator. Although ArrayList is obviously a better choice, there are times when the array is more useful.

(1) If the size of the list is already specified, most of the cases are stored and traversed.

(2) for traversing the base data type, although collections uses automatic boxing to mitigate the encoding task, it can also become slow on the list of basic types of the specified size.

(3) If you want to use a multidimensional array, it is easier to use [] [] than list<list<>>. What is the difference between 25.ArrayList and LinkedList?

ArrayList and LinkedList both 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 an O (1) complexity, but LinkedList stores a series of node data, each node connected to the previous and next node. So, despite the method of using an index to get elements, the internal implementation starts at the starting point, traverses the indexed node and then returns the element, with a time complexity of O (n), slower than ArrayList.

(2) inserting, adding, and deleting an element in the LinkedList is faster 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 a reference to 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.EnumSet is what.

Java.util.EnumSet is implemented using a collection of enumeration types. When a collection is created, all elements in the enumeration collection must come from a single specified enumeration type, either displayed or implied. Enumset is not synchronized and does not allow elements with null values. 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.

Vectors, HashTable, properties, and stack are synchronous classes, so they are thread-safe and can be used in multithreaded environments. The Java1.5 concurrency API includes collection classes that allow iterations to be modified because they all work on the clones of the collection, so they are safe in a multithreaded environment. 29. What is the Concurrency collection class?

The Java1.5 and contract (java.util.concurrent) contains a thread-safe collection class that allows you to modify the collection at iteration time. The iterator is designed to be fail-fast and throws concurrentmodificationexception. Some of the classes are: Copyonwritearraylist, Concurrenthashmap, Copyonwritearrayset. 30.BlockingQueue is what.

The

Java.util.concurrent.BlockingQueue is a queue that waits for the queue to become non-null when retrieving or removing an element, and waits for free space in the queue when an element is added. The Blockingqueue interface is part of the Java Collection framework that is used primarily to implement producer-consumer patterns. We do not need to worry about waiting for the producer to have available space, or the consumer has an object available because it is processed in the Blockingqueue implementation class. Java provides a centralized blockingqueue implementation, such as Arrayblockingqueue, Linkedblockingqueue, Priorityblockingqueue, Synchronousqueue, and so on. 31. Queues and stacks are the differences that list them.

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.