Java Collection Surface Questions

Source: Internet
Author: User
Tags addall comparable new set serialization concurrentmodificationexception

What is a 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: Vector, Stack, Hashtable, and array. With the extensive use of the collection, Java1.2 proposes a collection framework that encompasses all the set interfaces, implementations, and algorithms. Java has been going on for a long time with the use of generics and concurrent collection classes in a thread-safe way. It is also included in the Java bundle, blocking interfaces, and their implementations. Some of the advantages of the collection framework are as follows:

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

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

(3) You can reduce code maintenance costs by using the collection classes that are included with the JDK.

(4) reusability and operability.

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

Java1.5 introduces generics, and all of the collection interfaces and implementations use it in large quantities. Generics allow us to provide a set of object types that can accommodate a collection, so if you add any element of another type, it will be wrong at 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 it does not produce byte-code instructions for type checking.

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

Collection is the root interface for the collection hierarchy. A collection represents a set of objects that are the elements of that object. 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 abstraction of a mathematical set and is used to represent a collection, just like a deck of cards.

A list is an ordered collection that can contain repeating elements. You can access any element by its index. The list is more like an array of length dynamic transformations.

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

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, which are the elements of the object. How to maintain these elements is determined by the specific implementation of collection. For example, some collection implementations such as list allow repeating elements, while others such as set are not allowed. Many collection implementations have a public clone method. However, it is meaningless to put it in all implementations of the collection. This is because collection is an abstract representation. It is important to realize.

When dealing with specific implementations, the semantics and meaning of cloning or serialization only work. Therefore, a specific implementation should decide 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 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 part of the collection framework, the map is not a collection and the collection is not a map. Therefore, map inheritance collection meaningless, and vice versa.

If map inherits the collection interface, then where does the element go? Map contains the Key-value pair, which provides a way to extract a collection of key or value lists, but it is not suitable for a "set of object" specifications.

What is 6.Iterator?

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

What is the difference between 7.Enumeration and iterator interfaces?

The 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 blocks other threads from modifying the collection.

Iterators Replace enumeration In the Java collection framework. Iterators allow callers to remove elements from the collection, and enumeration cannot. To make its functionality clearer, the iterator method name has been improved.

8. Why is there no way to add elements to a collection like Iterator.add ()?

The semantics are unknown, and it is known that the iterator protocol does not guarantee the order of the iterations. Note, however, that Listiterator does not provide an add operation to ensure the order of the iterations.

9. Why doesn't the iterator 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 if it is added to the interface, each inheritance is to implement it, which makes no sense.

What is the difference between 10.Iterater and listiterator?

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

(2) iterator can only traverse forward, while Listiterator can traverse in both directions.

(3) Listiterator inherits from the iterator interface and adds some additional features, such as adding an element, replacing an element, and getting the index position of the previous or subsequent element.

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

1234567891011 list<string> Strlist = new arraylist<> (); //use For-each loop for &NBSP;&NBSP; system.out.println (obj); } //using iterator Iterator<string> it = Strlist.iterator (); while (It.hasnext ()) { &NBSP;&NBSP; string obj = It.next (); &NBSP;&NBSP; system.out.println (obj);

Using iterators is more thread-safe because it ensures that when the currently traversed collection element is changed, it throws Concurrentmodificationexception.

12. Through the iterator Fail-fast attribute, what do you understand?

Each 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 concurrentmodificationexception. Implementations of all iterator 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?

The Fail-fast property of iterator works in conjunction with the current collection, so it is not affected by any changes in the collection. All the 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, and fail-safe iterators never throw concurrentmodificationexception.

14. How do I avoid concurrentmodificationexception when iterating through a collection?

When traversing a collection, we can use concurrent collection classes to avoid concurrentmodificationexception, such as using Copyonwritearraylist instead of ArrayList.

15. Why does the iterator interface 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 the iterator used 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 is 16.UnsupportedOperationException?

Unsupportedoperationexception is an exception that is used to indicate that an operation is not supported. has been used extensively in JDK classes, the java.util.Collections.UnmodifiableCollection will throw this exception in all add and remove operations in the collection framework.

17. How does HashMap work in Java?

HashMap stores Key-value pairs in the Map.entry static inner class implementation. HashMap uses a hashing algorithm, which uses the hashcode () and Equals () methods in the put and get methods. When we call the Put method by passing Key-value, HashMap uses the key hashcode () and the hashing algorithm to find the index of the stored key-value pair. Entry is stored in LinkedList, so if there is a entry, it uses the Equals () method to check whether 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 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 questions about HashMap are capacity, load factor, and threshold adjustment. The default initial capacity of the HashMap is 32, and the load factor is 0.75. The threshold is the load factor multiplied by the capacity, whenever we try to add a entry, if the map size is larger than the threshold value, HashMap will re-hash the contents of the map and use a larger capacity. Capacity is always a power of 2, so if you know you need to store a large number of key-value pairs, such as caching data pulled from the database, it's a good idea to initialize the HashMap with the correct 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 values from the 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, then overwrite them instead of storing them in different places. Similarly, all collection classes that do not allow the storage of 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 (), 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 to the map, but before using them, 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 as mentioned earlier.

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

(4) The best practice for the user-defined key class is to make it 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, which resolves issues related to variability.

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

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

That's why string and integer are heavily used as hashmap keys.

What are the different collections views provided by the 20.Map interface?

The map interface provides three views of the collection:

(1) Set keyset (): Returns a set view of all the keys contained in the map. The collection is supported by map, and map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, the result of the iterator becomes undefined if the map is modified (except for the removal of the iterator itself). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing the corresponding mappings from the map. It does not support add and addall operations.

(2) Collection values (): Returns a Collection view of all value 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, the result of the iterator becomes undefined if the map is modified (except for the removal of the iterator itself). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing 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 map, and map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, the result of the iterator becomes undefined if the map is modified (in addition to the iterator's own removal and the entry returned by the iterator). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing 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, while 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 in Java1.4, and if you want to traverse the order, you can easily turn from HashMap to Linkedhashmap, but Hashtable is not, its order is unpredictable.

(4) HashMap provides a set traversal of key, so it is fail-fast, but Hashtable provides a enumeration traversal of key, which does not support fail-fast.

(5) Hashtable is considered a legacy class, and you should use Cocurrenthashmap if you seek to modify the map during iteration.

22. How do I decide whether to choose HashMap or TreeMap?

HashMap is the best choice for operations such as inserting, deleting, and locating elements in a map. 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 quicker to add elements to the HashMap, changing the map to TreeMap for an orderly 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 index-based and internally supported by an array.

(2) Both maintain the order in which they are inserted, and we can get the elements according to the insertion order.

(3) The iterator implementations of ArrayList and vectors are fail-fast.

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

Here are the different points of ArrayList and vectors.

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

(2) ArrayList is faster than vector, it is not overloaded because of synchronization.

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

What is the difference between 24.Array and ArrayList? When is it more appropriate to use an array?

Arrays can hold basic types and objects, whereas ArrayList can only hold objects.

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

The 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 the array is more useful.

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

(2) for traversing the base data type, although collections uses auto-boxing to alleviate the encoding task, working on a list of basic types of a specified size can also become slow.

(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?

Both ArrayList and LinkedList implement the list interface, but they are somewhat different.

(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 connected to the previous and next node. So, although there is a way to get an element using an index, the internal implementation is traversing from the starting point, traversing the node to the index and returning the element, with a time complexity of O (n), which is slower than ArrayList.

(2) inserting, adding, and deleting an element in 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 the LinkedList stores references 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.

What is 27.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 either displayed or implicit. The Enumset is not synchronized, and an element with a value of NULL is not allowed. It also provides some useful methods, such as copyof (Collection c), the of (E first,e...rest), and Complementof (Enumset s).

28. Which collection classes are thread-safe?

Vectors, HashTable, properties, and stacks 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 for iterations to be modified because they all work on the clone of the collection, so they are safe in a multithreaded environment.

29. What are the Concurrent collection classes?

The Java1.5 and bundle (java.util.concurrent) contains a thread-safe collection class that allows the collection to be modified at iteration time. Iterators are designed to be fail-fast and will throw concurrentmodificationexception. Some of the classes are: Copyonwritearraylist, Concurrenthashmap, Copyonwritearrayset.

What is 30.BlockingQueue?

Java.util.concurrent.BlockingQueue is a queue that waits for a queue to become non-empty 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 and is primarily used to implement producer-consumer patterns. We don't have to worry about waiting for the producer to have space available, or the consumer has an object available, because it's being processed in the Blockingqueue implementation class. Java provides centralized blockingqueue implementations such as Arrayblockingqueue, Linkedblockingqueue, Priorityblockingqueue, Synchronousqueue, and so on.

31. What are the queues and stacks, listing their differences?

Both stacks and queues are used to pre-store data. Java.util.Queue is an interface whose implementation class is in Java and in a contract. Queues allow FIFO to retrieve elements, but not always. The Deque interface allows you to retrieve elements from both ends.

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

A stack is a class that extends from a vector, and a queue is an interface.

What is the 32.Collections class?

Java.util.Collections is a tool class that contains only static methods that manipulate or return a collection. It contains the polymorphic algorithm of the operation set, returning a new set supported by the specified collection and some other content. This class contains methods for the collection of framework algorithms, such as binary search, sorting, mixing, and reverse order.

What is the 33.Comparable and comparator interface?

If we want to use the sort method of array or collection, we need to implement Java in the custom class to provide the comparable interface. The comparable interface has the CompareTo (T OBJ) method, which is used by the ordering method. We should override this method, which returns a negative integer, 0, or a positive integer if the "This" object is smaller, equal, or larger than the passed object argument. However, in most cases, we want to sort by 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 the Comparable.compareto (object o) method implementation can only be sorted based on one field, and we cannot select the field according to the order of the objects. The implementation of the compare (object O1, Object O2) method of the comparator interface requires the passing of two object parameters, if the first parameter is smaller than the second, a negative integer is returned, if the first one equals the second, 0 is returned, and if the first one is larger than the second, a positive integer is returned.

What is the difference between 34.Comparable and comparator interfaces?

The comparable and comparator interfaces are used to sort object collections or arrays. The comparable interface is used to provide a natural ordering of objects, 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 to use to sort a given set of objects.

35. How do we sort a group of objects?

If we need to sort an array of objects, we can use the Arrays.sort () method. If we need to sort an object list, we can use the Collection.sort () method. Two classes have overloaded methods for natural sorting (using comparable) or standard-based sorting (using comparator) sort (). Collections internally uses array sorting methods, all of which have the same performance, except that collections takes time to convert the list to an array.

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

Before being passed as a parameter, we can use the Collections.unmodifiablecollection (Collection C) method to create a read-only collection. This will ensure that any action that alters the collection will throw unsupportedoperationexception.

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

We can use Collections.synchronizedcollection (Collection c) to get a synchronized (thread-safe) collection based on the specified collection.

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

The Java Collection Framework provides common algorithm implementations, such as sorting and searching. The collections class contains these method implementations. Most algorithms manipulate the list, but some of them are available for all types of collections. Some algorithms have sort, search, mixed, and maximum minimum values.

39. What is an O in uppercase? Give me a few examples?

The uppercase O describes the performance of an algorithm in terms of a series of elements in the data structure. The collection class is the actual data structure, and we typically use the uppercase O to select the collection implementation based on time, memory, and performance. For example, the Get (index i) of the example 1:arraylist is a constant time operation that 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 iterate through all the elements to find the elements we need.

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

(1) Select the correct collection type as needed. For example, if you specify a size, we will choose an array instead of a ArrayList. If we want to traverse a map in order of insertion, we need to use TreeMap. If we don't want to repeat, we should use set.

(2) Some collection classes allow you to specify the initial capacity, so if we can estimate the number of stored elements, we could use it to avoid re-hashing or resizing.

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

(4) Always use type-safe generics to avoid classcastexception at run time.

(5) Using the immutable classes provided by the JDK as key to the map, you can avoid implementing hashcode () and Equals () yourself.

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

Java Collection Surface Questions

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.