Java Collections and generics __java

Source: Internet
Author: User
Tags data structures rehash concurrentmodificationexception
Java Collection Framework and generics
First the overall overview, the following figure is a Java Collection Framework class diagram    



HD class diagram pdf download Address: http://download.csdn.net/detail/mydream20130314/8574911

To put it simply, the list saves the lists of objects, the set saves the list of duplicates, and the map holds the key value pair mappings.
Here's a brief introduction: arraydeque<e>

Underlying data structure

List
Two-terminal queue

Description

The two-end queues implemented by this class do not have capacity limits or specify capacity for them

The iterator returned by this class is a fast-fail

This class is not thread-safe and does not support concurrent access

This class is likely to be faster than stack when used as a stack, faster than linkedlist when used as a queue

Most operations run at a fixed time, with exceptions including remove, Removefirstoccurrence, Removelastoccurrence, contains, Iterator.remove (), and bulk operations, which run at a linear time

Version

Since 1.6 priorityqueue<e>

Underlying data structure

An unbounded priority queue based on the priority heap
Minimum heap

Description

The priority queue is sorted by default in natural order, and the elements must be comparable and NOT NULL

You can sort it by providing a comparator

The capacity of the queue can be automatically expanded with the element or assigned a capacity

The iterator of this class does not guarantee that the elements are ordered

The class is not thread-safe, not a synchronized collection. Instead, the Priorityblockingqueue class of wire safety

This class implements the O (log (n)) time for queued and out team methods (offer, poll, remove () and add); Provide linear time for the Remove (object) and contains (object) methods; Provides a fixed-time version for fetching methods (peek, element, and size)

Since 1.5 arraylist<e>

Underlying data structure

List

Description

This class can randomly access elements, and the capacity expands automatically

Add and delete operations run at a linear time

Before adding a large number of elements, an application can use the Ensurecapacity action to increase the capacity of the ArrayList instance, which can reduce the number of incremental redistribution

This class is not thread-safe

The iterator for this class is fast failing

Version

Since 1.2 linkedlist<e>

Underlying data structure

Linked list

Description

This class can be used as a stack, a queue, or a two-terminal queue

The index operation will be traversed from the chain head or chain end

The class is not thread-safe, and the iterator is quick to fail

High performance when using a large number of inserts, deletions

Version

Since 1.2 stack<e>

Underlying data structure

List
LIFO stack

Description

This class extends the vector to provide the basic operation of the LIFO stack

The Deque interface and its implementation provide a more complete and consistent set for the LIFO stack operation, which should be used preferentially rather than this set. For example: Deque stack = new Arraydeque ();

Early stack implementations, now, Linkedlist,deque and so on provide stack operations

Version

Since 1.0 vector<e>

Underlying data structure

List

Description

This class is an array of objects that can be automatically expanded or reduced

The iterator for this class is fast failing

Starting with the Java 2 Platform v1.2, this class is improved to implement the List interface, making it a member of the Java collections Framework. Unlike the new collection implementations, vectors are synchronized enumset<e extends enum<e>> underlying data structures

Hash list Description

A private Set implementation that is used with an enumeration type
The iterators returned by the iterator method traverse these elements in their natural order, which is the order in which the enumerated constants are declared. The returned iterator is weakly consistent and will not return any effects to the set's modifications
Iterators are not thread safe.
All operations are run at a fixed time version

Since 1.5 enummap<e extends enum<e>,v>

Underlying data structure

Hash list

Description

A private MAP implementation that is used with the enumeration type
Enumeration mappings are maintained according to the natural order of their keys (in order to declare enumerated constants)

The returned iterator is weakly consistent and will not return any effects to the set's modifications
is not thread-safe.
All operations are run at a fixed time

Version

Since 1.5 hashset<e>

Underlying data structure

Hash table

Description

Allow only one element to be null
This class is actually supported by the HashMap instance, except that the key of the map is not used.
The iteration order of the class is indeterminate
This class is not thread-safe
The rapid failure behavior of the iterator for this class cannot be guaranteed

Version

Since 1.5 hashmap<k,v>

Underlying data structure

Hash table

Description

This class is based on a hash table map implementation. Provides an optional mapping operation.
You can use the null key and the null value the class is not thread-safe, and the iterator is fast failing. After the introduction of the hash table, the text has HashMap and hashtable comparison

Version

Since 1.5 linkedhashset<e>

Underlying data structure

Hash table

Description

hash table and link list implementations of Set interfaces with predictable iterative order. The difference between this implementation and HashSet is that the latter maintains a doubly linked list running on all entries. This list of links defines the sequence of iterations, that is, the order in which elements are inserted into the set (the insertion order). Note that the insertion order is not affected by elements that are reinserted in the set. (If S.add (e) is called immediately after S.contains (e) returns True, Element e is reinserted into set S.)

This implementation can protect customers from unspecified, hashset-provided, often disorganized sorting work without incurring increased costs associated with TreeSet. It can be used to generate a set copy that is the same as the original order, and is independent of the implementation of the original set:

void Foo (set s) {
     set copy = new Linkedhashset (s);
     ...
 }

This technique is particularly useful if the module uses input to get a set, copy the set, and then return the result of the order that the copy determines. (Customers typically expect content to be returned in the same order as they appear.)

This class provides all optional Set operations and allows null elements. As with HashSet, it provides stable performance for basic operations (add, contains, and remove), assuming that the hash function distributes the elements correctly to the storage segment. Because of the increased cost of maintaining a linked list, the performance is likely to be more than hashset lesser, except that: the time required for Linkedhashset iterations is proportional to the size of the set, regardless of capacity. HashSet iterations are likely to cost more because the iteration time required is proportional to its capacity.

Version

Since 1.4 linkedhashmap<k,v>

Underlying data structure

Hash table

Description
A hash table of the Map interface and a list of links are implemented with predictable iteration order. The difference between this implementation and HASHMAP is that the latter maintains a doubly linked list running on all entries. This list of links defines the order of iterations, which is usually the order in which the keys are inserted into the map (insert order). Note that if you reinsert the key in the map, the insertion order is unaffected. (If M.containskey (k) returns true before the call to M.put (K, v), the call will reinsert the key K into the map m. )

This implementation allows customers to avoid unspecified, often disorganized sorting work provided by HASHMAP (and Hashtable) without increasing the cost associated with TREEMAP. Use it to generate a mapped copy that is the same as the original order, regardless of the implementation of the original mapping:

    void foo (map m) {
        map copy = new Linkedhashmap (m);
        ...
    }     

This technique is especially useful if the module is used to get a map, copy the map, and then return the results of the order in which the copy is determined. (the customer usually expects the content returned in the same order as it appears.)

Provides a special construction method to create a linked hash map, which is the order in which the hash map is last accessed, from the most recent access to the most recent order (Access order). This mapping is ideal for building LRU caches. Invoking the put or get method will access the appropriate entry (assuming it still exists after the call completes). The Putall method generates an entry access for each mapping relationship for the specified mapping by specifying the order of the key-value mapping relationships provided by the mapped entry set iterator. No other method generates entry access. In particular, operations on the collection view do not affect the iteration order of the underlying mappings.

You can override the Removeeldestentry (Map.entry) method to enforce the policy so that the old mapping relationship is automatically removed when you add a new mapping relationship to the mapping.

This class provides all of the optional MAP operations and allows null elements. Like HashMap, it provides stable performance for basic operations (add, contains, and remove), assuming that the hash function distributes the elements correctly into the bucket. Because of the increased cost of maintaining a linked list, the performance is likely to be more than HashMap lesser, except that: the time required for Linkedhashmap collection view iterations is proportional to the size of the map. The HashMap iteration time is likely to be costly because it requires a proportional amount of time.

Version

Since 1.4 treeset<e>

Underlying data structure

Red-black tree (red and black)

Description

Navigableset implementation based on TREEMAP. The elements are sorted using the natural order of the elements, or sorted according to the Comparator provided when the set was created, depending on the constructor method used.

This implementation provides guaranteed log (n) time overhead for basic operations (add, remove, and contains)

Version

Since 1.2 treemap<k,v>

Underlying data structure

Red-black tree (red and black)

Description

Based on the NAVIGABLEMAP implementation of the red-black tree (Red-black). The mapping is sorted according to the natural order of its keys, or according to the Comparator provided when the mapping is created
This implementation provides guaranteed log (n) time overhead for ContainsKey, get, put, and remove operations
The class is not thread-synchronized and the iterator is fast failing
You can change the key value mapping by put (K,V)

Version

Since 1.2 hashtable<k,v>

Underlying data structure

Hash table

Description

Early map implementations, elements are not null
Default load factor (. 75)
The returned iterator is a quick failure
The enumeration returned by the Hashtable key and element method is not a fast failure
This class is not thread-safe
The biggest difference with HashMap is that hashmap allow keys or values to be null, and Hashtable are not NULL
After the introduction of the hash table, the text has HashMap and hashtable comparison

Version

Since 1.0 Fail-Safe and iterator iterators related

If a collection object creates iterator or Listiterator, and then another thread attempts to "structurally" change the collection object, a Concurrentmodificationexception exception is thrown. However, it is permissible for other threads to change the collection object through the set () method because it does not change the collection from "structurally". However, if you have made changes to the structure, and then call the set () method, you will throw a IllegalArgumentException exception.

Structural changes refer to the deletion or insertion of an element, which affects the structure of the Map hash table

Hash table is in addition to the order table, linked list, index table, another kind of linear table storage structure, almost in constant time through the key to get the value.

The hash table has two factors that determine its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is only the size of the hashtable at the time of creation. The load factor is a scale in which the hash table can reach full size before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the Hashtable is rehash (that is, the internal data structure is rebuilt, and the hash value is recalculated), which expands the hashtable to about twice times the original

Typically, the default load factor (. 75) seeks a tradeoff between time and space costs. The high load factor, while reducing the space overhead, also increases the cost of the query (which is reflected in the operations of most HASHMAP classes, including get and put operations). The initial capacity should be set to take into account the number of entries and their load factors required in the mapping in order to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, the rehash operation does not occur.

If a large number of mappings need to be stored in the map instance, setting a higher initial capacity is better than automatic rehash.

Hash algorithm:

An algorithm that maps key values to memory addresses can reduce the occurrence of "hash conflicts" by using an excellent hash algorithm

Hash conflict:

A hash conflict is the same as the address value after multiple key values are computed.
In the case of a "hash conflict", a single bucket stores multiple entries that must be sequentially searched for the difference between HashMap and Hashtable

HashMap and Hashtable both implement the map interface, but before deciding which one to use, we need to figure out the difference between them. The main differences are: thread safety, Synchronization (synchronization), and speed.

HashMap can be almost equivalent to Hashtable, except that HashMap is synchronized, and can accept null (HashMap can accept null key values (keys) and values (value), and Hashtable not).

HashMap is synchronized, and Hashtable is synchronized, which means that Hashtable is thread-safe, multiple threads can share a hashtable, and if there is no correct synchronization, Multiple threads cannot share hashmap. Java 5 provides Concurrenthashmap, which is an alternative to Hashtable, and is better than Hashtable extensibility.

Another difference is that the HashMap iterator (iterator) is a fail-fast iterator, while the Hashtable enumerator iterator is not fail-fast. So when there are other threads that change the structure of the hashmap (adding or removing elements), the concurrentmodificationexception will be thrown, but the remove () of the iterator itself Method removes an element, it does not throw a concurrentmodificationexception exception. But this is not a certain behavior, it depends on the JVM. This is also the difference between enumeration and iterator.

Because Hashtable is thread-safe and synchronized, it is slower than hashmap in a single-threaded environment. If you don't need to sync, you just need a single thread, so it's better to use HashMap performance than Hashtable. the difference between HashSet and HashMap

HASHMAP implements the map interface, HashSet implements the set interface.

HashMap Store key value pairs HashSet only stores objects

Use the put () method to place elements in a map using the Add () method to place the elements in a set

HashMap uses the key object to compute the Hashcode value HashSet uses the member object to compute the hashcode value, and for two objects the hashcode may be the same, so the Equals () method is used to determine the equality of objects, if two objects are different, Then return false

HashMap is faster because it is using unique keys to get objects HashSet is slower than HashMap

HashSet is essentially hashmap, he just uses the HashMap key section to see the source code

Public HashSet () {
    map = new hashmap<e,object> ();
}
Collection Tool Class collections
Collections provides a large number of static tools, operation sets, such as stable sorting, lookup, search, extraction, etc.
using synchronization Collections

Collection provides several ways to wrap a generic collection into a collection of thread synchronizations. SYNCHRONIZEDXXXX ()
For example: Map m = Collections.synchronizemap (HASHMAP);

If you are using JDK1.5 and above, consider using the Concurrent Collection tool in the Java package java.util.concurrent

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.