Summary of Java Collections
Collection是集合接口
| ———— set sub-interface: unordered, no repetition allowed.
| ———— List sub-interface: Ordered, can have repeating elements.
区别:Collections是集合类
Set and list comparison:
Set: The retrieval element is inefficient, the deletion and insertion efficiency is high, and insertions and deletions do not cause the element position to change.
List: And arrays, lists can grow dynamically, find elements efficiently, and insert deleted elements inefficiently because they cause other elements to change position.
Set and list specific subclasses:
Set
| ———— HashSet: Storing elements in a hash table, inserting deletes quickly.
List
| ———— ArrayList: Dynamic array
| ———— linkedlist: Linked list, queue, stack.
Extended
Array and Java.util.Vector
Vector is an old dynamic array that is thread-synchronized and inefficient, and is generally not in favor of use.
Linked Fast Reading Slow
Array Read fast Change slow
Hash between the two
Details 1) List Interface (inherited from collection interface) and its implementation class
The list interface and its implementation class are variable-capacity lists that access elements in the collection by index.
Features: The elements in the set are ordered and repeatable;
The list is represented in the data structure as: array and vector, linked list, stack, queue.
Implementation class:
-
ArrayList implements an array that is variable in size and can be accessed like a linked list. It provides functionality similar to the vector class but is out of sync, it is a list implemented in array mode, allowing fast random access.
-
LinkedList implements a linked list that provides the best sequential access for inserting and removing elements. A linked list defined by this class can also be used as a stack or as a queue. Provides the best sequential access, suitable for inserting and removing elements.
2), set set interface (inherit from collection interface) and its implementation class
Access to and manipulation of members in set is done through references to objects in set, so there can be no duplicate objects in the set.
Features: The elements in the collection are not sorted in a particular way, but simply adding objects to the collection is like putting something in your pocket.
Set also has a variety of variants, such as the ability to sort, such as TreeSet, which adds an object to a set of actions to be inserted into an ordered sequence of objects according to a comparison rule. It implements the SortedSet interface, which is the method of adding object comparisons. By iterating over the objects in the set, we can get an ascending set of objects.
Implementation class:
-
HashSet can quickly locate an element, it is important to note that the object that is deposited into the HashSet must implement the Hashcode () method;
-
TreeSet the elements into which they are stored.
3) Map map interface and its implementation class
The map is a separate interface and does not inherit from the collection. Map is a container that associates key objects with value objects.
Features: key does not allow repetition.
Mappings are significantly different from sets or lists, and each item in the map is paired, and map is the container that associates the key object with the value object. Each object stored in the map has an associated keyword (key) object that determines where the object is stored in the map, and must be supplied with the corresponding keyword when retrieving the object, as if looking up a word in the dictionary. The keyword should be unique, meaning that the key object in the map does not allow repetition, which is to ensure consistency of the query results.
The keyword itself does not determine where the object is stored, it needs to be processed over a hashing (hashing) technique, producing an integer value called a hash code, which is usually used as a bias, relative to the starting position of the memory region assigned to the map. This determines where the keyword/object pair is stored. Ideally, hash processing should result in a uniformly distributed value within a given range, and each keyword should have a different hash code.
Implementation class:
-
HASHMAP implements a key-to-value mapping hash table, which takes a key to the value object, does not have a sequence, gets the value through get (key), allows the storage of an empty object, and allows the key to be empty (since the key must be unique, of course there is only one);
-
HashTable implements an image, all keys must be non-empty. In order to work efficiently, the class defining the key must implement the Hashcode () method and the equal () method. This class is an inheritance of the previous Java implementation and is usually better used in other classes that implement the image.
-
Select TreeMap when the order of the elements is important, and use hashmap when the elements do not have to be stored in a particular order. The use of Hashtable is not recommended because HashMap provides all the similar features and is faster. HashMap can also be converted to synchronous when you need to use it in a multithreaded environment.
-
Properties are typically stored in the form of a key-value pair after the property file is read into the stream to facilitate reading of the data.
4), Iterator interface
The iterator interface is located in the Java.util package, which is an iterator that iterates over the collection.
A collection container (such as List, Set, map, etc.) itself provides a way to handle the placement and removal of elements, but a single selection of elements is restricted. So we're going to use iterator to select the element in the container, which converts the container into a sequence.
Some collection classes provide a function of content traversal through the Java.util.Iterator interface. These interfaces allow iterating over the collection of objects. Manipulate each element object in turn. When iterators is used, a collection snapshot is included when the iterator is obtained. It is usually not recommended to modify the collection province when traversing a iterator.
Iterator iter = Object.iterator ();
while (Iter.hasnext ()) {...}
Summary of Interview questions
-
What is the difference between iterator and listiterator?
Iterator: The collection can only be traversed forward, and is suitable for getting removed elements. Listierator: Inherits the iterator, can traverse the bidirectional list, also supports the element modification.
-
What is Haspmap and map?
Map is an interface, a part of the Java collection framework, used to store key-value pairs, and HashMap is a class that implements a map using a hashing algorithm.
-
What is the difference between HashMap and Hashtable?
Both are used to obtain data in a key-value way.
Hashtable is one of the original collection classes (also known as The Legacy Class).
HashMap is added as part of the new collection framework in version 1.2 of JAVA2. There is a difference between them:
- HashMap and Hashtable are roughly equivalent except for non-synchronous and null values (HASHMAP allows null values as key and value, while Hashtable cannot).
- HashMap cannot guarantee that the order of the mappings is constant, but as a subclass of HashMap Linkedhashmap, if you want to predict the sequential iterations (by default in order of insertion), you can easily replace the HashMap, if you use Hashtable is not so easy.
- The HashMap is not synchronous, and Hashtable is synchronous.
- Iterative HashMap uses a fast failure mechanism, and Hashtable is not, so this is the design consideration.
-
What does synchronization mean in the context of Hashtable?
Synchronization means that only one thread can modify the hash table at a point in time, and any thread needs to acquire an object lock before executing the Hashtable update operation, while other threads wait for the lock to be released.
-
What is called fast failure feature
Rapid failure from a high-level hierarchy is a response of a system or software to its failure. A fast-failing system is designed to instantly report any failure condition that could lead to failure, and it is often used to stop normal operations rather than trying to continue with potentially flawed work. When a problem occurs, the system quickly fails to make a false error alarm immediately. In Java, quick failures are related to iterators. If a iterator is created on the collection object, other threads are "structured" to modify the collection object, and the concurrent Modification exception (Concurrentmodificationexception) is thrown.
-
How do I synchronize the HashMap?
The HASHMAP can be synchronized by using map m = Collections.synchronizedmap (HASHMAP).
-
When to use Hashtable, when to use HashMap
The basic difference is that Hashtable synchronous HashMap is not, so whenever there are multiple threads accessing the same instance, the Hashtable should be used instead of hashmap. Non-thread-safe data structures provide better performance.
If there is a possibility in the future-you need to get a scheme for key-value pairs in order, HashMap is a good choice because there is a subclass of HashMap Linkedhashmap. So if you want predictable sequential iterations (by default in the order of insertions), you can easily replace HashMap with Linkedhashmap. It is not so easy to use the hashtable of the opposite view. At the same time if there are multiple threads accessing Hashmap,collections.synchronizedmap () can be substituted, generally hashmap more flexible.
-
Why is the vector considered to be obsolete or unofficially deprecated? Or why should we always use ArrayList instead of vectors?
You should use ArrayList instead of vectors because by default you are non-synchronous, vectors synchronize each method, you almost never do that, and usually you want to synchronize the entire sequence of operations. Synchronizing a single operation is also unsafe (if you iterate over a vector, you still need to lock it to prevent other threads from changing the collection at the same time). and more efficient. Of course there is also the cost of locking even if you don't need it, this is a bad way to access by default. You can always use Collections.sychronizedlist to decorate a collection.
In fact, vectors combine a set of "mutable arrays" and synchronize the implementation of each operation. This is another design flaw. Vector also has some legacy methods in enumerations and elements to get methods that are different from the list interface, if these methods in the code programmers tend to want to use it. Although enumerations are faster, they cannot be checked if the collection is modified during iteration, which can cause problems. For many of these reasons, Oracle has never claimed to abandon vectors.
-
What is the difference between Collection, set, and list?
There is no specified order between the collection objects, allowing duplicate elements and multiple null element objects; It is the parent class of the Set and list interface, and is the most general type of the collection interface;
There is no specified order between the set element objects, no duplicate elements are allowed, and at most one null element object is allowed;
The list of element objects has a specified order, allowing repeating elements and multiple null element objects;
-
Linkedlist,arraylist,vector,stack,queue difference? NodeList difference?
- LinkedList chained access, connected by pointers, is suitable for frequent insertions and deletions in the middle of a linked list.
- ArrayList is an array-like form that is stored by ordinal, with very fast random access.
- Vector vectors are stored according to each element ordinal, and the size of the array can grow dynamically, which is more efficient for high-capacity data storage.
- Stack stacks, advanced out of the array.
Comparison and selection of these classes: if it involves operations such as stack queues, the Stack,queue in list should be considered for quick insertion of deleted elements and should use LinkedList if you need to quickly randomly access elements, you should choose ArrayList if the program is in a single-threaded environment, Select non-synchronous classes if you are in multi-threading, select the synchronization class vector, stack, and Hashtable and their subclasses.
-
Relationship of Set and map
Set represents a set of unordered, cannot duplicate;
Map represents a collection of Key-value, which is an associative array. The key requirements of map are not repeated, without order. Combining all the keys of a map is set. Set KeySet ();
-
Vector and ArrayList differences
Vector provides synchronized modification methods, which are thread-safe versions of ArrayList
Principle Introduction
-
Summary of principle points of ArrayList realization
Reference documents
ArrayList is a mutable array asynchronous implementation of the list interface and allows all elements including null.
The underlying uses array implementations
The collection is a variable-length array, and when the array is expanded, the elements in the old array are re-copied to the new array, and each time the array capacity grows by approximately 1.5 times times its capacity, the cost of this operation is high.
With the fail-fast mechanism, when faced with concurrent modifications, the iterator will soon fail completely, rather than risking any uncertain behavior at some uncertain time in the future
-
Summary of principle points of linkedlist realization
Reference documents
LinkedList is a chain-stored linear table, essentially a doubly linked list, which implements the list and Deque interfaces. The deque represents a double-ended queue, which can be used as a queue or as a stack.
LinkedList is a doubly linked list asynchronous implementation of the list interface and allows all elements including null.
The underlying data structure is based on a doubly linked list, the data structure we call a node
A doubly linked list node corresponds to an instance of the class entry, and entry contains the member variable: previous,next,element. Where previous is the node's previous node, next is the node's next node, and element is the value that the node contains.
-
Summary of principle points of hashmap realization
Reference documents
HashMap is a non-synchronous implementation of a hash table-based map interface that allows NULL values and NULL keys, but does not guarantee the order of mappings.
The underlying uses an array implementation, and each item in the array is a linked list, which is a combination of arrays and linked lists
HashMap at the bottom of the key-value as a whole to deal with, this whole is a entry object. HashMap uses a entry[] array to hold all key-value pairs, and when a entry object needs to be stored, the key's hash algorithm is used to determine where it is stored in the array. Determines the storage location of the linked list in the array position according to the Equals method, and when a entry is needed, it will also find its storage location in the array according to the hash algorithm of key, and then remove the entry from the linked list in that position according to the Equals method.
HashMap for array expansion requires recalculation of the position of each element in the array after expansion, which consumes performance
Using the fail-fast mechanism, a modcount value is used to record the number of changes, and changes to hashmap content will increase this value. This value is assigned to the iterator's expectedmodcount during the iterator initialization, and in the iterative process, the modcount is judged to be equal to Expectedmodcount, and if not equal indicates that another thread has modified the map and throws the exception immediately
HashMap has two parameters that affect its performance: initial capacity and load factor. The default initial capacity is 16, and the load factor is 0.75. Capacity is the number of buckets (entry arrays) in the hash table, and the initial capacity is just the capacity at the time of creation of the Hashtable. A load factor is a scale in which a hash table can reach a full amount before its capacity increases automatically. Doubles the capacity by calling the Rehash method when the number of entries in the hash table exceeds the product of the load factor to the current capacity.
That is, you can put a maximum of 16*0.75=12 elements, when put 13th, HashMap will occur rehash,rehash a series of processing compared to affect performance, so when we need to store more elements to HashMap, it is best to specify the appropriate initial capacity and loading factor, Otherwise hashmap can only save 12 elements by default, and multiple rehash operations will occur.
The size of HashMap is 2^n regardless of how much x in your HashMap (x) is set. 2^n is the first number greater than X. If x=100, then the initial size of the HASHMAP should be 128. But 100/128=0.78, the size of the default load factor has been exceeded. So it will resize once and become 256. So the best result is still 256.
Hash generation algorithm may generate: Hashing collision DDoS vulnerability, causing system crashes
Hash Collision Vulnerability Reference
-
Summary of principle points of Hashtable realization
Reference documents
Hashtable is a synchronous implementation of a hash table-based map interface, with null values and NULL keys not allowed
The underlying uses an array implementation, and each item in the array is a single-linked list, which is a combination of arrays and linked lists
Hashtable at the bottom of the key-value as a whole to deal with, this whole is a entry object. Hashtable uses a entry[] array to hold all key-value pairs, and when a entry object needs to be stored, the key's hash algorithm is used to determine where it is stored in the array. Determines the storage location of the linked list in the array position according to the Equals method, and when a entry is needed, it will also find its storage location in the array according to the hash algorithm of key, and then remove the entry from the linked list in that position according to the Equals method.
-
Summary of principle points of concurrenthashmap realization
Reference documents
Concurrenthashmap allows multiple modifications to be performed concurrently, with the key being the use of lock separation techniques.
It uses multiple locks to control changes to different segments of the hash table, each of which is a small hashtable that has its own lock. As long as multiple concurrent occurrences occur on different segments, they can be performed concurrently.
Concurrenthashmap at the bottom of the key-value as a whole to deal with, this whole is a entry object. Hashtable uses a entry[] array to hold all key-value pairs, and when a entry object needs to be stored, the key's hash algorithm is used to determine where it is stored in the array. Determines the storage location of the linked list in the array position according to the Equals method, and when a entry is needed, it will also find its storage location in the array according to the hash algorithm of key, and then remove the entry from the linked list in that position according to the Equals method.
Unlike HashMap, Concurrenthashmap uses multiple sub-hash tables, that is, segments (Segment)
Concurrenthashmap allows multiple read operations to be performed concurrently, and read operations do not require locking. If you use traditional techniques, such as implementations in HashMap, if you allow the addition or deletion of elements in the middle of a hash chain, the read operation will get inconsistent data without locking. CONCURRENTHASHMAP implementation technology is to ensure that hashentry is almost immutable.
-
Summary of principle points of hashset realization
Reference documents
HashSet is supported by a hash table (actually a HashMap instance), does not guarantee the set iteration order, and allows null elements to be used.
Based on the HASHMAP implementation, the API also encapsulates the behavior of HashMap, which can be referenced HashMap
-
Summary of principle points of linkedhashmap realization
Reference documents
Linkedhashmap inherits from HashMap, and the underlying uses a hash table and a doubly linked list to hold all the elements, and it is unsynchronized, allowing null values and NULL keys to be used.
The basic operation is similar to the parent class HashMap, and by overriding the HashMap correlation method, the saved element entry in the array is redefined to implement its own list of links properties. In addition to saving references to the current object, the entry also holds a reference to the previous element, before, and the next element after, forming a two-way link list.
-
Summary of principle points of linkedhashset realization
Reference documents
For Linkedhashset, it inherits from HashSet and is based on Linkedhashmap. The Linkedhashset bottom uses Linkedhashmap to hold all the elements, inheriting and hashset, all of which are identical to HashSet.
-
Principles of HashMap and HashSet
The hashmap is stored in an array-linked list, and the element is entry. When adding <Key,Value> to HashMap, the hashcode of the key determines the entry storage location, when the hashcode of the key of the two entry object is the same, the Equals of key () The method return value determines whether the overwrite behavior (returns true) or adds a new entry (return false) to the list header. Collection values (), returns the collection object, but cannot add elements, primarily for traversal. Custom classes need to override the Equals and Hashcode methods if they are placed in HashMap or HashSet.
-
Principles of TreeMap and TreeSet
The bottom of the treemap is stored with a red-black tree, and each entry corresponds to a node of the tree, and the treemap element is sorted from small to large by default. V put (Key K, Value v) is essentially an insertion algorithm for a two-fork sort tree
The difference between HashMap in JDK1.7 and 1.8
Reference documents
-
In JDK1.7
Use a entry array to store the data, use the hashcode of the key to determine where the key will be placed in the array, if the hashcode is the same, or the result of hashcode modulo is the same (hash collision), Then these keys will be positioned in the same lattice of the entry array, which will form a linked list.
In the case of hashcode particularly poor, such as all key hashcode are the same, the list may be very long, then the put/get operation may need to traverse the list
In other words, time complexity degrades to O (n) in the worst case.
-
In JDK1.8
Use a node array to store the data, but this node may be a linked list structure or a red-black tree structure.
If the hashcode of the inserted key is the same, then these keys will also be positioned in the same lattice of the node array.
If there are no more than 8 keys in the same lattice, use the linked list structure to store them.
If there are more than 8, then the Treeifybin function is called and the linked list is converted to a red-black tree.
So even if the hashcode is exactly the same, because of the red-black tree's characteristics, to find a particular element, but also only the cost of O (log n) that is put/get operation of the worst time complexity is only O (log n)
Really want to take advantage of JDK1.8, there is a limit:
Key object, the compare interface must be implemented correctly
If the Compare interface is not implemented or is not implemented correctly (for example, all compare methods return 0)
That JDK1.8 's hashmap is actually slower than JDK1.7.
Summary of Java collection classes