Java Collections Framework surface by

1 set of generic framework What are the advantages?

Java1.5 introduces a generic, all the collection interfaces and implementations use a lot of it. Generics allow us to offer a type of object can hold as a collection, so if you add any other type of element, it will complain at compile time. This avoids the appearance ClassCastException at run time, because you will get an error message at compile time. Generic clean also makes the code, we do not use the explicit conversion and instanceOf operator. It also brings benefits to running, because no type checking of bytecode instructions.

2 Collection why not inherit Cloneable and Serializable interface?

Collection Interface specifies a set of objects, the object that is its elements. How to maintain these elements from the Collection of the specific implementation decisions. For example, some implementations allow such Collection List of duplicate elements, while others such as Set is not allowed. Collection has a lot to achieve a public clone method. However, to implement it on all of the collection is of no significance. This is because the Collection is an abstract expressionist. It is important to realize. When dealing with a particular realization, the sequence of a cloning or semantic meaning and only play a role. Therefore, specific implementations should it decide how to clone or sequence of, or whether it can be cloned or serialized. Cloning and sequencing of the Authorization in all implementations, resulting in less flexibility and more restricted. Specific implementation should decide whether it can be cloned and serialization.

3 Why Map interface does not inherit the Collection interface?

Despite the Map interface and its implementations are part of a collection of frames, but Map is not a collection, the collection is not Map. Therefore, Map Collection meaningless succession, and vice versa. If you inherit Map Collection interface, then the element where to go? Map comprising key-value pairs, or a method of extracting a key that provides a list of the set value, but it is not suitable for "a set of objects" specification.

The difference between 4 Enumeration and Iterator interface?

Enumeration twice as fast as Iterator, but also use less memory. Enumeration is very basic, but also to meet basic needs. However, compared with Enumeration, Iterator more secure, because when a collection is being traversed, it will prevent other threads to modify the collection.

Iterator replaced the Java Collections Framework Enumeration. Iterators allow the caller to remove elements from the collection, and Enumeration can not do. To make it function more clearly, the iterator method name has undergone improvements.

What is the difference between 5 Iterater and ListIterator?

  1. We can use the Iterator to traverse Set and List collections, ListIterator can only be traversed List.
  2. Iterator traversal can only move forward, and LIstIterator traverse in both directions.
  3. ListIterator interface inherits from the Iterator, then add some additional features, such as adding an element, a replacement element, acquires the index position of the front or rear elements.

6 What are the different ways to traverse a List there?

You can use for-each loop or iterator to traverse a List, which use an iterator more thread-safe, because it ensures that, when the current iteration of the collection element is changed, it will throw a ConcurrentModificationException.

7 through fail-fast iterator property, you know what?

Every time we try to get the next element of time, Iterator fail-fast property to check for any changes in the structure of the current collection. If you find any changes, it throws ConcurrentModificationException. Collection implemented by all the Iterator is designed fail-fast (except ConcurrentHashMap CopyOnWriteArrayList and such concurrent collection class).

8 iteration of a set time, how to avoid ConcurrentModificationException?

In traversing a collection, we can use concurrent collections classes to avoid ConcurrentModificationException, such as the use CopyOnWriteArrayList, instead of ArrayList.

9 Why Iterator interface is not specific implementation?

Iterator interface defines the methods through the collection, but its implementation is the responsibility of the collection implementation class. Each class can be set for the return Iterator traversal achieved Iterator has its own internal class. This allows collections to choose iterator is fail-fast or fail-safe of. For example, the ArrayList iterator is fail-fast, and CopyOnWriteArrayList iterator is a fail-safe.

What 10 UnsupportedOperationException that?

UnsupportedOperationException is used to indicate that the operation does not support exceptions. Has been widely used in JDK class, this exception will be thrown in all add and remove operations in the collection framework java.util.Collections.UnmodifiableCollection.

11 In Java, HashMap How does it work?

HashMap implemented key-value pairs stored in the static inner Map.Entry class. HashMap using the hash algorithm, the put and get methods, it uses the hashCode () and equals () method. When we put on when calling the method, HashMap using Key hashCode () and hash algorithm by passing key-value store index to find key-value pairs. Entry is stored in the LinkedList, so if the entry exists, it uses equals () method to check whether the transfer of key already exists, if there is, it will cover the value, if not, it will create a new entry and save. When we call the get method by passing key, use it again hashCode () to find the index into the array, and then use the equals () method to find the right Entry, and then returns its value. About HashMap other more important issue is the capacity, load factor and threshold adjustment. HashMap default initial capacity is 16, the load factor is 0.75. Threshold is multiplied by the coefficient for the load capacity, whenever we try to add an entry, if the size of the map is greater than the threshold when the content HashMap map will be re-hash, 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 from the database to pull the inside, with the correct capacity and load factor to initialize HashMap is a good practice.

What is the importance of () and equals () method 12 hashCode?

Key object using HashMap hashCode () and equals () method to determine the index key-value pairs. When we tried to get the value from the HashMap, these methods will be used. If these methods are not properly implemented, in this case, two different Key may produce the same hashCode () and equals () output, the HashMap will assume they are the same, and then covering them, they instead stored in different places. Similarly, all collections are not allowed to store duplicate data using hashCode () and equals () to find duplicate, so they are very important to achieve the right. Implement equals () and hashCode () should follow the following rules:

  1. If o1.equals (o2), then o1.hashCode () == o2.hashCode () always is true.
  2. If o1.hashCode () == o2.hashCode (), does not mean o1.equals (o2) will be true.

13 Can we use any class key as the Map?

We can use any kind as the Map key, but before using them, you need to consider the following:

  1. If the class overrides the equals () method, it should also override the hashCode () method.
  2. All instances of a class need to follow the rules associated with the equals () and hashCode (). Please refer to the rules mentioned before.
  3. If a class does not use equals (), you should not use it in hashCode () in.
  4. User-defined best practice is to make the key class is immutable, so, the hashCode () value may be cached, better performance. Immutable classes can also ensure hashCode () and equals () will not change in the future, which would solve the problems associated with the variable.

For example, I have a class MyKey, use it in the HashMap.

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

That is why the key String and Integer is used as HashMap of heavy use.

14 Map interface provides a set of what are the different views?

Map interface provides three collection views:

  1. Set keyset (): Set a view of all the key returns the map contains. A collection is supported by the map, the map changes will be 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), the result will be the iterator is undefined. Supported by a set of element removal Remove, Set.remove, removeAll, retainAll Iterator and clear operations, removing the corresponding mapping from the map. It does not support add and addAll operations.
  2. Collection values ​​(): returns a value Collection view all included in a map. This collection supported by the map, the map changes will be 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 result will be the iterator is undefined. Supported by a set of element removal Remove, Set.remove, removeAll, retainAll Iterator and clear operations, removing the corresponding mapping from the map. It does not support add and addAll operations.
  3. Set> entrySet (): Returns a map that contains all of a bell collection view mappings. This collection supported by the map, the map changes will be reflected in the collection, and vice versa. When an iterator is traversing a set, if the map is modified (except for setValue removal operation, and the entry of the iterator returned by the iterator itself outside), the result will be the iterator is undefined. Supported by a set of element removal Remove, Set.remove, removeAll, retainAll Iterator and clear operations, removing the corresponding mapping from the map. It does not support add and addAll operations.

15 HashMap and HashTable What's the difference?

  1. HashMap allows key and value is null, and HashTable is not allowed.
  2. HashTable is synchronized, and HashMap is not. So HashMap for single-threaded environment, HashTable for multi-threaded environment.
  3. Introduced in Java1.4 a subclass LinkedHashMap, HashMap, if you want to traverse order, you can easily shift from HashMap LinkedHashMap, but HashTable not the case, its order is unpredictable.
  4. Set HashMap provides the key to traverse, so it is fail-fast, but HashTable provide key to traverse the Enumeration, it does not support fail-fast.
  5. HashTable is considered to be a legacy of the class, if you seek to change the Map when iteration, you should use CocurrentHashMap.
  6. Because the thread safety problems, HashMap HashTable than a little high efficiency.
  7. If not specified when creating the initial capacity value, Hashtable default initial size is 11, after each expansion, into the original capacity of 2n-1. HashMap default initialization size is 16. After each expansion, capacity becomes 2 times the original. When you create if given the capacity of the initial value, Hashtable will direct you to use a given size, and HashMap will expand its size is a power of 2.

How 16 decided to use HashMap or TreeMap?

Map to insert, delete and locating elements such operations, HashMap is the better choice. However, if you need an ordered collection of key traverse, TreeMap is a better choice.

17 What are the similarities and differences ArrayList and the Vector?

ArrayList and Vector similarities:

  1. Both are based on the index, an array of internal support.
  2. Both maintain the order of insertion, we can get the elements insert according to the order.
  3. ArrayList and Vector iterators are fail-fast realization of.
  4. Both ArrayList and Vector allow null values, the elements may be random access using the index value.

ArrayList and the Vector in different places:

  1. Vector is synchronized, but not ArrayList. However, if you are seeking to make changes to the list when iteration, you should use CopyOnWriteArrayList.
  2. ArrayList is faster than Vector.
  3. ArrayList is more common, because we can use the Collections utility class to easily obtain the synchronization list and read-only list.

What's the difference 18 Array and ArrayList?

  1. Array basic types and can accommodate objects, while receiving only ArrayList object.
  2. Array is specified size, but ArrayList size is not fixed.
  3. Array does not provide ArrayList so versatile, such as addAll, removeAll iterator, and so on. Although ArrayList is obviously a better choice, but maybe sometimes Array better use.

19 When more suitable Array?

  1. Size of the list has been designated, in most cases the storage and traversing them.
  2. For traversing the basic data types, although Collections packing to reduce the use of automatic coding tasks, but the work will become on the basic types of specified size list very slow.
  3. If you want to use multidimensional arrays, use [] [] is easier than List>.

What's the difference 20 ArrayList and LinkedList?

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

  1. ArrayList and LinkedList are not synchronized, that is not guaranteed to be thread safe.
  2. Object Arraylist underlying array is used; the LinkedList underlayer using a doubly linked list.
  3. ArrayList using storage array, the time complexity of the insert and delete elements of the impact receiving element location; storing the LinkedList linked list, so for add (E e) of the method of inserting, deleting elements from the time complexity of the impact element position, approximately O (1), if i is to insert and delete elements in the specified position if (add (int index, E element) is approximately the time complexity of O (n)), because of the need to move to a specified location and then inserted.
  4. LinkedList does not support efficient random element access, and support for ArrayList. Quick access to fast random access is via the object element is an element number (corresponding to the get (int index) method).
  5. Waste of space ArrayList is mainly reflected in the list at the end of the list will reserve some space capacity, cost and space LinkedList is reflected in each of its elements need to consume more space than ArrayList (due to the direct deposit and direct successor precursors and data).

What 21 BlockingQueue that?

Java.util.concurrent.BlockingQueue is a queue, or remove a retrieval element during the time, it will become non-empty queue; when adding an element, it will wait for space available in the queue. BlockingQueue interface is a part of the Java Collections Framework, used to realize the producer - consumer model. We do not need to worry about waiting for the producer space is available, or the consumer has available objects, as it were BlockingQueue implementation class to be dealt with. Java provides centralized BlockingQueue, such ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue ,, SynchronousQueue and so on.

What 22 Collections class is?

Java.util.Collections is a utility class that contains only static methods. It contains a set of polymorphic arithmetic operation, returns a new set specified by the set and other supported content. This class contains a collection of methods frame algorithms, such as binary search, sort, reverse, etc., and mixed.

23 Comparable and Comparator difference of?

Comparable difference between Java and two comparators of Comparator

24 How do we sort a group of objects?

If we need to sort an array of objects, we can use Arrays.sort () method. If we need to sort a list of objects, we can use Collection.sort () method. Both classes have a natural ordering (using Comparable) or overloaded method based on the sort ordering criteria (using Comparator) of (). Collections internal use array sorting method, all they both have the same performance, but it takes time to Collections list to an array.

25 When a collection is passed as a parameter to a function, how we can ensure that the function can not change it?

Before passed as a parameter, we can create a read-only collection using Collections.unmodifiableCollection (Collection c) method, which will ensure that nothing will change in the collection of an UnsupportedOperationException.

26 How do we set the set from there to create a synchronized collection?

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

Set of 27 general algorithm framework to achieve what?

Java Collections Framework provides a common algorithm, such as sorting and searching. Collections class contains these methods. List of Most algorithms are operating, but part of the collection of all types are available. Part of the algorithm for sorting, searching, mixed, maximum and minimum values.

28 List, Set, Map distinguish three?

  1. List: List stores a set of interfaces are not unique (there may be multiple elements reference the same object), the object orderly
  2. Set: do not allow duplicate collections. There will be no more elements refer to the same object.
  3. Map: Use key-value pair storage. Map will maintain and Key associated value. Key two can reference the same object, but can not repeat Key, typically of type String Key, but may be any object.

29 RandomAccess

RandomAccess Interface reads as follows:

public interface RandomAccess {
}

View source we found that in fact nothing RandomAccess interface definition. So, in my opinion, but the interface is a flag RandomAccess nothing. What identity? Logo implement this interface with random access capabilities.

In binarySearch method, it is to judge whether RamdomAccess instance incoming list, and if so, call indexedBinarySearch method, if not, then call iteratorBinarySearch method.

    public static <T>
    int binarySearch(List<? extends Comparable<? super T>> list, T key) {
        if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
            return Collections.indexedBinarySearch(list, key);
        else
            return Collections.iteratorBinarySearch(list, key);
    }

ArrayList implements RandomAccess interface, and LinkedList not achieved. why? I think it is related to the structure and underlying data! ArrayList array is the bottom, and the bottom is LinkedList list. An array of natural support random access, time complexity is O (1), so called fast random access. Need to traverse the list to a specific location to access the elements of a specific location, time complexity is O (n), it does not support fast random access. ArrayList implements RandomAccess interface illustrated his fast random access. RandomAccess interface is just identity, not to say ArrayList implement the RandomAccess interface that has the fast random access function!

Select 30 list traversal way?

  1. Implements list RandomAccess interface preference for general circulation, followed foreach
  2. Unrealized list RandomAccess interface preference iterator traversal (foreach to traverse through the underlying iterator is implemented), the large size of the data, do not use ordinary for loop

The difference between 31 HashMap and HashSet?

  1. It is based on the underlying HashSet HashMap implementation
  2. HashSet implements Set interface, HashMap implements Map
  3. Storing only the object HashSet, HashMap for storing a key-value pairs
  4. HashSet use the Add method to add elements, HashMap using put method to add elements

How to check for duplicate 32 HashSet

When you join the objects HashSet, HashSet will first calculate the hashcode value of the object to determine the position of the object added, will also be compared with other hashcode value added objects, if there is no match of hashcode, HashSet assumes that the object is not repeated . But if the object has the same hashcode value found, then call the equals method to check hashcode equal objects will be really different. If they are the same, HashSet will not let join a successful operation.

The default behavior hashCode () is to create a unique value to objects on the heap. If no override hashCode (), then the two objects are not equal class anyway (even if these two objects point to the same data).

== 33 equals the difference between

== Analyzing two variables or examples are not directed to the same memory space, equals the value of two variables are determined or examples points to the memory space is not the same

Why 34 HashMap length is a power of 2?

In order to allow efficient access HashMap, less impact as possible, that is to try to put the data is evenly distributed. Hash values ​​range value -2147483648 to 2147483647, probably add up to around 4 billion mapping space, as long as the hash function mapping was more evenly loose, general application is difficult to occur collision. But the problem is an array of four billion length, the memory is not fit. So the hash value can not be directly used with. Also the length of the array do first modulo operation before use, in order to obtain the remainder to be stored is the position corresponding to the array index. This array is subscripted calculated (n - 1) & hash (n array representing length). This also explains why HashMap length is a power of two.

How does this algorithm should design it?

First, we might think of using modulo operation% to achieve. However, the focus here: modulo (%) the operation if the divisor is a power of 2 is equivalent to a reduction of its divisor AND (&) operation (i.e. hash% length == hash & (length-1) is provided that the length is the n-th power of 2). And the binary bit operation &,% with respect to the operation efficiency can be improved, which explains why HashMap length is a power of two.

35 summarizes a set of underlying data structures frame

List

  • Arraylist: Object Array
  • Vector: Object Array
  • LinkedList: doubly linked list (for the circular list before JDK1.6, JDK1.7 canceled cycle)

Set

  • HashSet (random, unique): HashMap based implementation, the underlying element to store using HashMap
  • LinkedHashSet: LinkedHashSet inherited from HashSet, and its interior is achieved through LinkedHashMap. Somewhat similar to what we said before LinkedHashMap its interior is the same HashMap based implementation, but still a little bit of difference
  • TreeSet (order only): red-black tree (self-balancing binary tree sort)

Map

  • HashMap: Before JDK1.8 HashMap of arrays and linked lists composed of an array of HashMap is the main, the list is mainly to resolve hash collision exists ( "zipper method" to resolve the conflict). After JDK1.8 has made significant changes in resolving hash collision, when the chain length is greater than the threshold value (the default is 8), into a red-black tree list to reduce the search time
  • LinkedHashMap: LinkedHashMap inherited from HashMap, so it is still based on the underlying structure is a hash zipper and a list or an array composed of red-black tree. Further, a LinkedHashMap on the basis of the above structure, an increase of a doubly-linked list, so that the above structure can be maintained on the key insertion order. Simultaneously by corresponding operation of the linked list, the access order to achieve associated logic.
  • Hashtable: composed of an array of linked lists, arrays are subject HashMap, the list is mainly to resolve hash collision exists
  • TreeMap: red-black tree (self-balancing binary tree sort)

The difference between 36 fail-fast and fail-safe in?

Thinking face questions: What is the difference java rapid failure (fail-fast) and the security failure (fail-safe) is?

37 CopyOnWrite container Comments?

CopyOnWrite container that is copy-on-write vessel. After the popular understanding is that when a container to add elements, not add to the current container directly, but first current container Copy, copy a new container, and then add a new container element, it has added elements, then the original reference point to the new container vessels. The advantage of this is that reading can be complicated by the CopyOnWrite container, without the need to lock, because the current container does not add any elements. Therefore, the container is also a separate read and write CopyOnWrite thought, reading and writing of different containers.

CopyOnWrite concurrent containers used for reading and writing less concurrency scenarios. For example whitelist, blacklist, the merchandise category to access and update scenarios, if we have a search site, users of this website's search box, enter a keyword to search for content, but do not allow certain keywords are searched. These keywords can not be searched will be placed on a blacklist among the blacklist is updated every night. When a user searches, checks the current key is not in the blacklist them, if, you can not search prompt.

CopyOnWrite the following disadvantages:

  1. Memory consumption problem: because the replication mechanism CopyOnWrite write, so when during a write operation, the memory will also be stationed memory, old objects and object newly written two objects. If these objects occupy memory is relatively large, so this time is likely to cause frequent Yong GC and Full GC.
  2. Data consistency problems. CopyOnWrite container can only ensure that the final data consistency can not guarantee real-time data consistency. So if you want to write data to the immediately able to read, do not use CopyOnWrite container.

Reference: What Java collection framework? Some say the advantages Collections Framework?
Read the whole network Java Collections Framework summary of common questions of surface 20k!

发布了113 篇原创文章 · 获赞 206 · 访问量 1万+

Guess you like

Origin blog.csdn.net/Geffin/article/details/103462476