Java Container Class Summary

Source: Internet
Author: User
Tags addall int size object object set set

The Java container class is a Java-provided toolkit that contains commonly used data structures: collections, linked lists, queues, stacks, arrays, mappings, and so on. Starting from this article will open a series of detailed analysis of each member of the Java container, including source code analysis, performance analysis, comparison between different containers, etc., the link will be updated synchronously in this article and the top Beauvennes.

The Java container can be divided into 4 parts: list lists, set sets, map mappings, tool classes (iterator Iterators, enumeration enumeration classes, arrays, and collections)

Container class Framework

Java Container Toolkit Framework diagram:

Through, you can grasp two basic subjects, namely collection and map.

    1. Collection is an interface that is a highly abstracted collection that contains the basic operations and properties of a collection. The collection contains the list and set of the two major branches.

      The list is an ordered queue, and each element has its index. The index value of the first element is 0. The list implementation class has LinkedList, ArrayList, Vector, Stack.
      Set is a collection that is not allowed to have duplicate elements. The implementation class for set has Hastset and TreeSet. HashSet relies on HashMap, which is actually implemented through HashMap; TreeSet relies on treemap, which is actually implemented by TreeMap.

    2. Map is a mapped interface, which is a Key-value key-value pair. Each element in the map contains "one key" and "key corresponding to value".

      Abstractmap is an abstract class that implements most of the APIs in the map interface. And Hashmap,treemap,weakhashmap are inherited from Abstractmap.
      Although Hashtable inherits from dictionary, it implements the map interface.

    3. Iterator is a tool that iterates through a collection, that is, we usually iterate through the collection through the iterator iterator. We say that collection relies on iterator because the collection implementation class implements the iterator () function and returns a iterator object. Listiterator is specifically designed to traverse the list.

    4. Enumeration is an abstract class introduced in JDK 1.0. Functions, like iterator, also traverse collections, but enumeration are less powerful than iterator. In the above block diagram, enumeration can only be used in Hashtable, Vector, and stack.

    5. Arrays and collections are the two tool classes that manipulate arrays and collections.

With the overall framework above, we then analyze each class separately.

Collection interface

Collection is defined as follows:

public interface Collection<E> extends Iterable<E> {}

It is an interface, a highly abstracted collection that contains the basic operations of a collection: adding, deleting, emptying, traversing (reading), being empty, getting the size, protecting an element, and so on.

All classes in Java that implement the collection interface must provide two standard constructors, one without parameters, to create an empty collection, and a parameter constructor with collection parameters for creating a new collection. This new collection has the same elements as the incoming collection.

Collection's API:

Abstract Boolean         Add (E object) Abstract Boolean         addall (collection<? extends e> Collection) abstract void            Clear () Abstract Boolean         contains (Object object) Abstract Boolean         Containsall (collection<?> Collection) Abstract Boolean         equals (Object object) abstract int             hashcode () Abstract Boolean         isEmpty () Abstract iterator<e>     Iterator () Abstract Boolean         Remove (Object object) Abstract Boolean         RemoveAll (collection<?> Collection) Abstract Boolean         retainall (collection<?> Collection) abstract int             Size () abstract <T> t[]         toArray (t[] array) abstract object[]        ToArray ()

  

List interface

The list is defined as follows:

public interface List<E> extends Collection<E> {}

List is an interface that inherits from collection, which is a list that is one of the collections. List is an ordered queue, each element in the list has an index, the index value of the first element is 0, and the index value of the subsequent element is +1. Unlike set, duplicate elements are allowed in the list.

Official document: A List is a collection which maintains an ordering for its elements. Every element in the List have an index. Each element can thus is accessed by it index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to sets, where elements has to be unique.

About the API aspect. Since list is inherited from the collection interface, it naturally contains all the function interfaces in collection, and since list is an ordered queue, it also has its own API interface. There are mainly "add, delete, get, modify elements at the specified location", "get sub-queues in list" and so on.

Collection apiabstract Boolean Add (E object) Abstract Boolean addall (collection<? extends e> Colle ction) abstract void Clear () Abstract Boolean contains (Object object) Abstract Boolean Containsall (collection<?> Collection) Abstract Boolean equals (Object object) abstract int hashcode () abstract Boolean isEmpty () abstract iterator<e> Iterator () Abstract Boolean Remove (Object object) Abstract B Oolean RemoveAll (collection<?> Collection) Abstract Boolean retainall (collection<?> Collection) abstract int size () abstract <T> t[] ToArray (t[] array) abstract object[] ToArray ()//compared with CO Llection,list new api:abstract void Add (int location, E object) Abstract boolean addall (int locati On, collection<? Extends E> collection) abstract E get (int location) abstract int IndexOf (Object object) Abstract int LastIndexOf (Object object) abstract listiterator<e> listiterator (int location) abstract L Istiterator<e> Listiterator () abstract e remove (int location) Abstract e Set (i NT location, E object) abstract list<e> sublist (int start, int end)

The implementation of the list interface collection mainly includes: ArrayList, LinkedList, Vector, Stack.

ArrayList

ArrayList is defined as follows:

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList is a dynamic array and is the most common collection we use. It allows any element that conforms to the rule to be inserted even including null. Each of the ArrayList has an initial capacity:

private static final int DEFAULT_CAPACITY = 10;

As the elements in the container continue to increase, the size of the container increases as well. A capacity check is carried out each time an element is added to the container, and the expansion is performed when the overflow is fast. So if we are clear about the number of elements inserted, it is better to specify an initial capacity value, to avoid excessive expansion operations and waste time, efficiency.

Size, IsEmpty, get, set, iterator, and listiterator operations are all run at a fixed time. The add operation runs at the allocated fixed time, that is, adding n elements requires an O (n) time (because of the expansion, this is not just adding elements that can be as simple as allocating fixed-time overhead).

ArrayList specializes in random access. At the same time ArrayList is not synchronous.

LinkedList

LinkedList is defined as follows:

public class LinkedList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable

The same implementation of the list interface LinkedList and ArrayList different, ArrayList is a dynamic array, and LinkedList is a doubly linked list. So it provides an additional Get,remove,insert method at the first or the end of the LinkedList in addition to the basic operating method of the ArrayList.

Due to the way the implementation is different, LinkedList cannot be accessed randomly, and all of its operations are performed according to the needs of the doubly linked list. An operation that is indexed in a list iterates through the list from the beginning or end, saving half the time from one end near the specified index. The advantage of this is that you can insert and delete operations in the list at a lower cost.

As with ArrayList, LinkedList is also unsynchronized. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list when the list is created:

List list = Collections.synchronizedList(new LinkedList(…));

Vector

The vector is defined as follows:

public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable

Similar to ArrayList, but vectors are synchronous. So vector is a dynamic array of thread safety. It operates almost the same as ArrayList.

Stack

The stack is defined as follows:

public class Stack<E> extends Vector<E> {}

Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created as an empty stack.

Set interface

The set is defined as follows:

public interface Set<E> extends Collection<E> {}

Set is an interface that inherits from collection, and set is a collection that does not include duplicate elements. It maintains its own internal ordering, so random access doesn't make any sense. As with list, it also runs NULL, but only one. Because of the particularity of the set interface, all elements in the incoming set set must be different,

About the API aspect. The set API is exactly the same as the collection.

The set interface is implemented with the following sets: HashSet, TreeSet, Linkedhashset, Enumset.

HashSet

HashSet is defined as follows:

public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

HashSet is the fastest collection of queries because it is internally implemented with Hashcode. The collection element can be null, but only one null is placed. The order of its inner elements is determined by the hash code, so it does not guarantee the set's iteration order, especially because it does not guarantee that the order will be constant.

TreeSet

TreeSet is defined as follows:

public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable

TreeSet is a two-tree implementation, based on the TreeMap, generates a set that is always in the sorted state, implemented internally by TreeMap, and does not allow null values to be placed. It is ordered by using the natural order of the elements, or by the Comparator provided when the set is created, depending on the construction method used.

Linkedhashset

Linkedhashset is defined as follows:

public class LinkedHashSet<E> extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable

The Linkedhashset collection also determines where the element is stored, based on the hashcode value of the element, but it maintains the order of the elements using the linked list. This makes the elements appear to be saved in an insertion order, that is, when the collection is traversed, Linkedhashset will access the elements of the collection in the order in which they are added. Linkedhashset performance is better than hashset when iterating through all the elements in the set, but the performance is slightly inferior to hashset at insert time.

Enumset

Enumset is defined as follows:

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
implements Cloneable, java.io.Serializable

All values in Enumset must be values of the specified enumeration type, and its elements are ordered in order to determine the order in which the enumeration values are defined in the enumeration class. The Enumset collection does not allow the addition of a null element, or a NullPointerException exception is thrown. The Enumset class does not expose any constructors to create an instance of the class, and the program should create the Enumset object through the static method it provides, for example:

public static void Main (string[] args) {        //creates an enumset empty collection, specifying that its collection element is an enumeration value of season1 Enumset<myenum>eset1 = Enumset.noneof (Myenum.class); Create a Enumset collection where the collection element is the entire enumeration value in season Enumset<myenum>eset2 = Enumset.allof (Myenum.class);} Enum MyEnum {      BLACK, white, RED, BLUR, GREEN, YELLOW  }

Consider an example of the difference between storage elements:

Static Collection Fill (collection<string> Collection) {collection.add ("rat"); Collection.add ("cat"); Collection.add ("dog"); Collection.add ("dog"); return collection;} public static void Main (string[] args) {System.out.println (Fill (New hashset<string> ())); SYSTEM.OUT.PRINTLN (Fill (New treeset<> ())); SYSTEM.OUT.PRINTLN (Fill (New linkedhashset<> ()));}

The HashSet is implemented as a hash table, and the order of storage is meaningless. If the order of storage is important, you can use TreeSet, which saves the object in ascending order of comparison, or, using Linkedhashset, saves the element in a sequence that is added. Of course they are thread insecure.

Result:[rat, Cat, Dog][cat, dog, Rat][rat, cat, dog]

  

Map interface

Unlike the list and set interfaces, a map is a collection of key-value pairs that provide a key-to value mapping. In map it guarantees a one by one correspondence between key and value. This means that a key corresponds to a value, so it cannot have the same key value, but the value can be the same.

The implementation Map collection is: HashMap, HashTable, TreeMap, Weakhashmap.

HashMap

HashMap is defined as follows:

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Implemented in a hash table data structure, the location of the object is computed by a hash function, which is designed for fast querying, which defines an array of hash tables (entry[] table), which converts the hash address of an element into an index stored in a group by a hash conversion function, if there is a conflict, A hash list is used to string all elements of the same hash address, possibly by looking at the source of the Hashmap.entry, which is a single-linked list structure.

HashTable

Hashtable is defined as follows:

public class Hashtable<K,V> extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable

It is also implemented as a hash table data structure, which is also used in the form of a hash list when resolving conflicts with HashMap. Hashtable inherits the dictionary class and implements the map interface. Where the dictionary class is the abstract parent class for any class (such as Hashtable) that can map keys to corresponding values. Each key and each value is an object. In any Dictionary object, each key is associated with at most one value. Map is the "Key-value key-value pair" interface. Hashtable uses "Zipper method" to realize hash table but performance is lower than HashMap.

TreeMap

TreeMap is defined as follows:

public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable

Ordered hash list, implement SortedMap interface, the bottom layer through red black tree realization.

Weakhashmap

Weakhashmap is defined as follows:

public class WeakHashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>

Before talking about Weakhashmap, look at the references in Java (intensity descending)

    1. Strong reference: A reference to a universal object declaration, there is no GC
    2. Soft references: Useful but not required, two recoveries before a memory overflow occurs
    3. Weak references: can only survive until the next GC, whether or not memory is sufficient
    4. Virtual reference: The only purpose is to receive a system notification when this object is GC

A hash table-based map implemented with weak keys. In Weakhashmap, when a key is no longer in normal use, its entry is automatically removed. More precisely, for a given key, the presence of its mapping does not prevent the garbage collector from discarding the key, which makes the key a terminating, terminated, and then recycled. When a key is discarded, its entry is effectively removed from the map, so the behavior of the class differs from the other map implementations. Null values and NULL keys are supported. The class has similar performance characteristics to the HashMap class and has the same initial capacity and load factor for the performance parameters. Like most collection classes, this class is out of sync.

Iterator

Iterator is defined as follows:

public interface Iterator<E> {}

Iterator is an interface that is an iterator to a collection. The collection can traverse the elements in the collection through iterator. Iterator provides an API interface that includes whether the next element exists, gets the next element, and deletes the current element.
Note: Iterator is a fail-fast mechanism when traversing collection. That is, when a thread a passes through iterator to traverse a collection, if the contents of that collection are changed by other threads, thread a accesses the collection and throws an Concurrentmodificationexception exception, resulting in a fail-fast event. For more details on fail-fast, we will explain it in the following section.

Iterator's API:

Abstract Boolean Hasnext () abstract E next () abstract void Remove ()

Finally, we summarize the general framework with a picture, and then we will start to analyze it in detail.

Links: http://alexyyek.github.io/2015/04/06/Collection/

Java Container Class Summary

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.