Java Collection Framework

Source: Internet
Author: User

Collection interface

    • Collection is the most basic set interface, and a collection represents a set of object, the collection element (Elements).
    • 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 with 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 iterator that iterates through the collection of each element in the iterator, which is unordered through the traversal of the.

Typical usage is as follows:

Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
List Interface
    • The list is an ordered collection, using this interface to precisely control 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.
    • 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.
    • The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

LinkedList class
    • The LinkedList implements a list interface that allows null elements. In addition, LinkedList provides an additional Get,remove,insert method. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque).
    • Note that LinkedList is not synchronized . If multiple threads access a linkedlist at the same time, you must implement access synchronization yourself. Another workaround is to construct a synchronized list:list list = collections.synchronizedlist (new LinkedList (...) when the list is created.

    1. LinkedList is an implementation class for the List interface
    2. LinkedList There are some unique methods that List does not have
    3. LinkedList is a linear linked-list structure
    4. the realization of LinkedList

linkedlist<e> list = new linkedlist<e> ();

linkedlist<e> list = new linkedlist<e> (Collection c);

    1. common methods of LinkedList

List.add (e);

List.add (index,e);

List.addfirst (e);

List.addlast (e);

List.get (index);

List.getfirst ();

List.getlast ();

ArrayList class
    • ArrayList implements a variable-sized 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.
    • 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.

A) ArrayList implementation class

    1. ArrayList is an implementation class for the List interface
    2. The ArrayList class is a dynamic array of a linear queue structure
    3. How to produce a ArrayList collection

list< generics > list = new arraylist< generics > ();

list< generics > list = new arraylist< generics > (Collection c);

    1. Common methods of ArrayList

Add method

List.add (Element);

Insert method

List.add (position , element );

Get method

E e = list.get (position);

Get collection length

int len = List.size ();

**************************************************************************************

Traverse

i mport java.util.ArrayList; import java.util.Arrays;
Import Java.util.Iterator;Import java.util.List;PublicClasstraversallist {Http://www.cnblogs.com/interdrp/p/3663602.htmlPublicStaticvoidMain (String args[]) {list<string> List =new arraylist<string> (arrays.aslist ( "Tom",  "Jane",  "Jerry"); //Method 1 General traversal of the collection class, from an earlier version, with an iterator iterative Iterator it1 = List.iterator (); while (It1.hasnext ()) {System.out.println (It1.next ());} //Method 2 A generic traversal of the collection class, from an earlier version, iterate with an iterator for (Iterator it2 = List.iterator (); It2.hasnext ();) {System.out.println (It2.next ());} //Method 3 enhanced for loop traversal for (String value:list) {System.out.println ( Value); } //Method 4 general type for loop traversal for (int i = " Span class= "Hljs-number" >0;i < List.size (); i + +) {System.out.println (List.get (i))}}}            
*************************************************************************************************** Vector class

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 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.

Comparison of vectors, ArrayList and LinkedList
    1. 1.Vector is thread-synchronized, so it is thread-safe, and ArrayList and LinkedList are non-thread-safe. If you do not take into account the security factors of the thread, generally with ArrayList and linkedlist efficiency is higher.
    2. 2.ArrayList and Vector are implemented based on dynamic array data structure, LinkedList data structure based on linked list.
    3. 3. If the number of elements in the collection is greater than the length of the current collection array, the vector growth rate is 100% of the current array length, while the ArrayList growth rate is 50% of the current array length. If you use large data volumes in the collection, vector has some advantages; Use ArrayList to have advantage.
    4. 3. If you look for data at a given location, the vectors and ArrayList use the same time, and the time is O (1), while the LinkedList needs to traverse the lookup, which takes time O (i) and is less efficient than the previous two.
    5. 4. If moving and deleting data at a given location takes 0 (n-i) n for total length, you should consider using LinkedList at this time because it takes 0 (1) to move the data at a specified location.
    6. 5. For inserting data at a specified location, Linedlist is dominant because ArrayList is moving data.

set Interface
    • Set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.
    • Obviously, the constructor of a set has a constraint that the passed-in collection parameter cannot contain duplicate elements.
    • Note: Variable objects (Mutable object) must be handled with care. If a mutable element in a set changes its state, causing Object.Equals (Object) =true will cause some problems.

**********************************************************************************************************

import java.util.*;

PublicClassTraversalset {PublicStaticvoid main (String args[]) {list<string> List = new arraylist<> (arrays.aslist (" Jerry "); set<string> set = new hashset<> (); Set.addall (list); //Method 1 General traversal of the collection class, from an earlier version, with an iterator iterative Iterator it1 = Set.iterator (); while (It1.hasnext ()) {System.out.println (It1.next ());} 
//Method 2 general traversal of the collection class, from an earlier version, iterate with an iterator for (Iterator it2 = Set.iterator (); It2.hasnext ();) {System.out.println (It2.next ());} //Method 3 enhanced for loop traversal for (String value:set) {System.out.println ( Value); } }}

*************************************************************************************************************** ***********************

Map Interface

Note that map does not inherit the collection interface, and map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value.

The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.

 *************************************************************************************

Traversal details please visit history

*************************************************************************************************************** *****************

Hashtable class
    • Hashtable inherits the map interface to implement a key-value mapped hash table. any object that is not empty (non-null) can be either a key or a value.
    • Add data using put (key, value), take out the data using get (key), the time overhead for these two basic operations is constant.
    • The Hashtable adjusts performance through the initial capacity and load factor two parameters. Normally the default load factor 0.75 is a good way to achieve a balanced time and space. Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations like get and put.
    • Because an object that is a key will determine the position of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods. The hashcode and Equals methods inherit from the root class object.
    • The Hashtable is synchronous.

HashMap class

HashMap and Hashtable are similar, except that HashMap is non-synchronous and allows NULL, which is null value and null key. However, when HashMap is treated as collection (the values () method can return collection), its iterative sub-operation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the initialization capacity of the hashmap too high or load factor too low.  

TreeMap class
    • HashMap quickly finds its contents by Hashcode, and all the elements in TreeMap are kept in a fixed order, orderly.
    • HashMap is the best choice for inserting, deleting, and locating elements in a map. But if you want to traverse the key in natural order or in a custom order, TreeMap is better. The implementation of Hashcode () and Equals () is clearly defined by the key class that is required to be added using HashMap.
    • TreeMap has no tuning option because the tree is always in equilibrium.

Weakhashmap class

Weakhashmap is an improved hashmap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally.

  Summary
    • If it involves operations such as stacks, queues, and so on, you should consider using the list, LinkedList if you need to quickly insert, delete elements, or if you need to quickly randomly access elements, you should use ArrayList.
    • If the program is in a single-threaded environment, or if access is done only in one thread, it is more efficient to consider non-synchronous classes, and if multiple threads may operate on a class at the same time, the synchronized class should be used.
    • Pay special attention to the operation of the hash table, and the object as key should correctly replicate the Equals and Hashcode methods.
    • When using map, it is best to use HashMap or Hashtable to find, update, delete, new, or to make a natural order or custom key sequence traversal of map, preferably using TreeMap;
    • Try to return the interface rather than the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client code does not have to be changed. This is for abstract programming.

More commonly, there are four kinds of ArrayList LinkedList TreeMap HashMap.

Java Collection Framework

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.