Summary of the Java Collection Class of the predecessors

Source: Internet
Author: User
Tags dateformat

JAVA collection Classes Introduction and use     class relationships   iterable (interfaces)      │     └--collection (interface)          ├-list (interface)           │├-linkedlist    (Construction synchronization: List List = Collections.synchronizedlist (new LinkedList (...)); )          │├-ArrayList   out of sync            │└-Vector      Sync           │└--Stack     Sync          └-Set              ├--EnumSet              ├--hashset--linkedhashset              └--TreeSet    Map ├--hashtable ├--hashmap--linkedhashmap └--weakhashmap    Map Interface:      |      +--weakhashmap: 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. This implementation is not synchronous.       |      +--TREEMAP: The map is sorted according to the natural order of its keys, or according to the Comparator provided when the mapping is created. Depending on the construction method used. This implementation is not synchronous.       |      +--HASHMAP: the implementation of a hash table-based MAP interface. This implementation provides all the optional mapping operations and allows NULL values and NULL keys to be used. (The HashMap class is roughly the same as Hashtable except for non-synchronous and null-allowed use.) This class does not guarantee the order of the mappings, especially because it does not guarantee that the order is constant. This implementation is not synchronous.       |      +--SortedMap: further provides a Map of the overall ordering of the keys. The mapping is sorted according to the natural order of its keys, or by the Comparator that are typically provided when an ordered map is created. This order is reflected when iterating over the collection view of an ordered map (returned by the EntrySet, KeySet, and Values methods). To use this sort method, you also need to provide some additional action (this interface is SortedSet).     Collection Interface:      |      +--set interface: A collection that does not contain duplicate elements. More formally, set does not contain element pairs that satisfy e1.equals (E2) E1 and E2, and contains a maximum of one null element. As its name implies, this interface mimics the mathematical set abstraction.       |      |      |       +--HashSet: This class implements the Set interface, which is supported by a hash table (actually a HashMap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant. This class allows the use of NULL elements. This class provides stable performance for basic operations, and this implementation is not synchronous.       |      |      |       +--linkedhashset: Hash table and link list implementation with a Set interface with predictable iteration order. This implementation differs from HashSet in that the latter maintains a double-link list that runs on all items. This list of links defines the order of iterations, that is, the order in which the elements are inserted into the set (insert order). Note that the insertion order is not affected by the elements that are reinserted in the set. This implementation is not synchronous.       |      |      |       +--TreeSet: 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 construction method used. This implementation provides a guaranteed log (n) time overhead for basic operations (add, remove, and contains). This implementation is not synchronous.       |      +--list interface: Ordered collection (also known as sequence). Users of this interface can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (the position in the list), and search for the elements in the list.              |              +--The implementation of the variable size array of the Arraylist:list interface. All optional list operations are implemented and all elements, including NULL, are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list. (This class is roughly equivalent to the vector class, except that this class is not synchronized.) Each ArrayList instance has a capacity. This capacity refers to the size of the array used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, their capacity increases automatically. The details of the growth strategy are not specified, as it is not just the addition of elements that can be as simple as allocating fixed-time overhead. This implementation is not synchronous.              |              +--The link list implementation of the Linkedlist:list interface. Implements all optional list operations, and allows all elements (including null). In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue, or double-ended queue. Provides a first-in, out-of-queue operation (FIFO). This implementation is not synchronous.              |              +--the Vector:vector class can implement an array of objects that can grow. Like an array, it contains components that can be accessed using an integer index. However, the size of the vector can be increased or reduced as needed to accommodate the addition or removal of items after the vector is created. This implementation is synchronous with .      Collection Interface   collection is the most basic collection interface, and a collection represents a set of object, the collection element (Elements). Some collection allow the same elements while others do not. Some can sort and others can't. The Java SDK does not provide classes that inherit directly from collection, and the Java SDK provides classes that inherit from collection, such as list and set.   All classes that implement the collection interface must provide two standard constructors: a parameterless constructor is used to create an empty collection, and a constructor that has a collection parameter is used to create a new collection. This new collection has the same elements as the incoming collection. The latter constructor allows the user to copy a collection.   How do I traverse every element in the collection? Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that uses the iteration to access each element of the collection one at a time. Typical usage is as follows:  Iterator it = Collection.iterator (); Get an iteration sub   while (It.hasnext ()) {  Object obj = It.next ();//Get Next element  }  by collection Two interfaces derived from the port are list and set. The   list interface   List is an ordered collection that allows precise control of where each element is inserted. The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of java.   Unlike the set mentioned below, List allows the same elements.   In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.   ImplementationCommon classes for the list interface are Linkedlist,arraylist,vector and stacks.     LinkedList   LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque).   Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list:  list = collections.synchronizedlist (new LinkedList (...) when the list is created.     ArrayList   ArrayList implements a variable-size array. It allows all elements, including null. ArrayList is not synchronized.   Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time. www.2cto.com    each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity automatically increases as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.   Like LinkedList, ArrayList is also asynchronous (unsynchronized).     vector   vectors are very similar to ArrayList, but vectors are synchronous. The iterator created by the vector, although the same interface as the iterator created by ArrayList, but because the vector is synchronous, when a iterator is created and is being used, another thread changes the state of the vector (for example, Some elements have been added or removed, Concurrentmodificationexception will be thrown when the iterator method is called, so the exception must be caught.     Stack class   stack inherits from Vector, implementing 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.      */    Package myapp.data;  import myapp.model.article;    Import java.text.dateformat;  Import java.text.parseexception;  Import java.util.*;  Import java.util.map.entry;    public class Collectionmethodtest {             private static list<article> list=new ArRaylist<article> (6);            public static void Initialize () Throws parseexception{                       DateFormat df = dateformat.getdateinstance (Dateformat.long, locale.france);           List.add (new article (1, "NBA1", "Carl1", "NBA Start1", Df.parse (" 2010-01-1 "), 1);           List.add (new article (2," NBA2 "," Carl2 "," NBA Start2 ", Df.parse (" 2010-01-2 "), 2));           List.add (new article (3, "NBA3", "Carl3", "NBA Start3", Df.parse ("2010-01-3"), 3));            List.add (new article (4, "NBA4", "Carl4", "NBA Start4", Df.parse ("2010-01-4"), 4);           List.add (new article (5, "NBA5", " Carl5 "," NBA Start5 ", Df.parse (" 2010-01-5 "), 5));           List.add (new article (6, "NBA6", "Carl6", "NBA Start6", Df.parse (" 2010-01-6 "), 6);      }                   //lists often allow duplicate elements, allow null elements, order       //Prototypes: public interface list <E> extends collection<e>      //Common implementation class:    abstractlist, ArrayList, LinkedList, Stack, vector       public void Listtest () {     & nbsp;           }            //hashmap: Allow null values and NULL keys, out of sync, implement the map interface and Abstractmap abstract class      //prototype: Public Class Hashmap<k,v> extends abstractmap<k,v> implements Map<k,v>, Cloneable, serializable       public void Hashmaptest () {  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;  System.out.println ("--------hashmap traversal------");                       Map<integer, string> map=new Hashmap<integer ,string> ();           for (article a:list) {                Map.put (A.getid (), A.gettitle () +a.getcontent ());           }         // Get all the keys to the map            set<integer> keys=map.keyset ();         //Get all the values of map            Collection<string> values=map.values ();         //Returns the mapping relationship contained in this mapping Set view.           Set<map.entry<integer, string>> setentry=Map.entryset ();         //Use iterator Walker traversal            System.out.println ("--------traverse------with the iterator Walker");           iterator<entry<integer,string>> it = setentry.iterator ();           while (It.hasnext ()) {              Entry<integer,string> e = It.next ();               System.out.println ("Id:" +e.getkey () + "Description:" +e.getvalue ());          }         /use for traversal            System.out.println ("--------Use for traversal------");          for ( entry<integer,string> e:setentry) {               System.out.println ("Id:" +e.getkey () + "Description:" +e.getvalue ());          }      }             //set: A collection that does not contain duplicate elements. More formally, the set does not contain elements that meet e1.equals (E2) to E1 and E2, and contains a maximum of one null element       //prototype: public interface set<e& Gt Extends collection<e>      //Implementation class:    Abstractset, Enumset, HashSet, Linkedhashset, TreeSet, jobstatereasons,copyonwritearrayset       public void Settest () {            set<string> set=new hashset<string> ();           Set.add ("No1");            Set.add ("No2");           set.add ("No3");       } } 

Excerpt from Twoicewoo's column

Summary of the Java Collection Class of the predecessors

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.