About Java Set frame face questions (including answers) on _java

Source: Internet
Author: User
Tags addall inheritance serialization concurrentmodificationexception

What is the 1.Java set frame? What are some of the advantages of a 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 only one value at most.

Some of the other interfaces are queue, dequeue, SortedSet, SortedMap, and Listiterator.

4. Why collection not inherit from 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 does the map interface 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, 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.

What's 6.Iterator?

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.

What is 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 don't you 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's 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, what do you understand?

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's 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 do you 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 specific implementation of the iterator interface?

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.

What's 16.UnsupportedOperationException?

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. How does HashMap work in Java?

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 are the different collection views 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.

This is about the Java Collection Framework interview question, is not the Java Collection Framework has a certain understanding, the following next for you to share the next chapter on the Java set frame face test questions.

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.