Java Collection Framework

Source: Internet
Author: User

The data structure has far-reaching influence on the program design, in the process-oriented C language, the database is described by struct, and in object-oriented programming, the data structure is described by the class, and contains the method of manipulating the data structure.

In the Java language, the designer of the Java language makes a number of specifications (interfaces) and implementations of the commonly used data structures and algorithms (the classes that implement the interfaces specifically). All abstract data structures and operations (algorithms) are collectively referred to as the Java Collection Framework (javacollectionframework).

Java programmers in the specific application, do not have to consider the data structure and algorithm implementation details, only need to use these classes to create some objects, and then directly applied to it, which greatly improve the efficiency of programming.

1. First say set and list:

1.1. Set sub-interface: unordered, not allowed to repeat. List sub-interface: Ordered, can have repeating elements. The specific difference is

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. < corresponding classes have hashset,treeset>

List: And arrays, lists can grow dynamically, find elements efficiently, and insert deleted elements inefficiently because they cause other elements to change position. < corresponding classes have arraylist,linkedlist,vector>

Set and list specific subclasses:

2.2. < example comparison >

HashSet: Storing elements as a hash table, inserting deletes quickly.

ArrayList: Dynamic array, LinkedList: Linked list, queue, stack.

Vector is an old dynamic array that is thread-synchronized and inefficient, and is generally not in favor of using

1.Collection interface

Collection is the most basic set 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. JAVASDK does not provide classes that inherit directly from collection, JAVASDK provides classes that inherit from collection "subinterfaces" 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 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 iteration that uses the iteration to access each element of the collection one at a time. Typical usage is as follows:

Iteratorit=collection.iterator ();//Get an iteration

while (It.hasnext ()) {

Objectobj=it.next ();//Get the next element

}

The two interfaces that are derived from the collection interface are list and set.

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

Unlike the set mentioned below, the 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.

The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

2.1.LinkedList class

The LinkedList implements a list interface that allows 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 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 when the list is created:

Listlist=collections.synchronizedlist (Newlinkedlist (...));

2.2.ArrayList class

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.

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 increase the efficiency of insertion (automatically increase the length of the judgment will be wasted time!) )。

Like LinkedList, ArrayList is also unsynchronized (unsynchronized). (Extended reading: The copyonwritearraylist provided in the Java.util.concurrent package provides thread-safe ArrayList, but it is implemented by creating a new copy of the underlying array when the add and set changes are made, so it is more expensive to use resources

(source code here: Publicboolean Add (e e) {

Final Reentrantlock lock =this. Lock;

Lock.lock ();

Try {

object[] elements = GetArray ();

int len = elements.length;

object[] newelements = Arrays. copyOf (Elements,len + 1);

Newelements[len] = e;

SetArray (newelements);

return True;

} finally {

Lock.unlock ();

}

}),

However, if there is frequent traversal, the traversal is much better than the synchronous traversal of the change (write and modify) operation, and it also allows for the existence of a NULL element)

2.3.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. storage operations can be optimized by using capacity and ensurecapacity operations, as well as capacityincrement domains, as discussed earlier , ( The vector's iterator and Listiterator methods translate iterators to support the fail-fast mechanism, so if other threads have modified the map during the use of iterators, Then the concurrentmodificationexception will be thrown, which is called Fail-fast strategy. The official explanation for this is that the collection classes in the Java.util package return fail-fast iterators, which means that they assume that the collection does not change its contents when the thread iterates through the contents of the collection. If the Fail-fast iterator detects that a change was made during the iteration, it throws Concurrentmodificationexception, which is an uncontrolled exception. )

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

There are several practical methods of stack

Boolean

Empty ()
Tests whether the stack is empty.

E

Peek ()
View the object at the top of the stack, but not remove it from the stack.

E

Pop ()
Removes the object at the top of the stack and returns the object as the value of this function.

E

Push (Eitem)
Press the item onto the top of the stack.

Int

Search (Objecto)
Returns the position of the object in the stack, with a base of 1.

3. Set interface:

The set has exactly the same interface as the collection, so there is no additional functionality, unlike the previous two different lists. In fact set is collection, but behaves differently. (This is a typical application of inheritance and polymorphic thinking: behavior that behaves differently.) Set does not save duplicate elements (more responsible for how the elements are judged)
Set: Each element that is stored in the set must be unique because set does not save duplicate elements. The element that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained. (I change the yellow background where the name gets the following features)


HashSet: It does not allow duplicate elements, does not guarantee the order of the elements in the political and political collections, you can make an example to see that the added field is not the same as the traversal, allowing the inclusion of a value of NULL elements, but there can be only one null element (not allowed to repeat!) )。

TreeSet: A collection of functions such as sorting, which is automatically inserted into an ordered sequence of objects by a comparison rule when the object element is added to the collection, and guarantees that the collection element is composed in ascending order.

A) (when retrieving large amounts of information, TreeSet is more efficient than araaylist and is guaranteed to be completed in log (n) time).

b) TreeSet is a useful tree structure to store information, each node will save a pointer object, pointing to the parent node, the left branch, the right branch, compared to the ArrayList is a simple array containing elements, because of this, it accounted for more than ArrayList memory.

c) It is also faster to treeset insert elements than ArrayList because when an element is inserted anywhere in the ArrayList, the average half of the list is moved, an O (n) time is required, and the implementation of the TreeSet depth traversal query requires only O (log (n)) (Common is, set query slow, insert fast, list query fast, insert full,.) TODO: I'll write an algorithm to test the article specific analysis ... )


Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (the Order of insertions). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.

There are several better ways to Ps:set:

RemoveAll (collection<?> c)

Removes the elements in the set that are contained in the specified collection (optional operation).

Boolean retainall (collection<?> c)

Preserves only those elements in the set that are contained in the specified collection (optional operation).

Containsall (collection<?> c)

Returns True if this set contains all the elements of the specified collection.

4.Queue data structure

This knowledge involves threading more, and the thread-based oral reference to this article

http://blog.csdn.net/a512592151/article/details/38454745

function method of 5.Map

Java defines an interface java.util.Map for the mappings in the data structure; it has four implementation classes, namely HashMap Hashtable linkedhashmap and TreeMap

Map is primarily used to store health-value pairs, which are given a value based on the key, so the key is not allowed to repeat, but the allowed value repeats.

Hashmap is the most commonly used map, which stores data according to the hashcode value of the key, which can be obtained directly from the key, with fast access speed. HashMap allows a maximum of one record's key to be null, allowing multiple records to have a value of NULL; HashMap does not support thread synchronization, where multiple threads can write HashMap at any one time, and may result in inconsistent data. If synchronization is required, you can use the collections Synchronizedmap method to make the HashMap capable of synchronizing.

Hashtable is similar to HashMap, unlike the following: it does not allow logging of keys or values to be empty; It supports thread synchronization, where only one thread can write hashtable at any one time, thus causing the Hashtale to be slower to write.

Linkedhashmap saves the order in which records are inserted, and when traversing linkedhashmap with iterator, the first record must be inserted first. It is slower than hashmap when traversing.

TreeMap is able to sort its saved records by key, by default in ascending order, or by specifying a sort comparer, and when traversing treemap with iterator, the resulting records are sorted out.

Package Com.hxw.t2;import Java.util.hashmap;import Java.util.hashtable;import java.util.iterator;import Java.util.linkedhashmap;import Java.util.map;import Java.util.treemap;public class Maptester {public static void init ( Map map) {if (map = null) {String key = null;for (int i = 5; i > 0; i--) {key = new Integer (i). toString () + ". 0"; map.p UT (Key, key.tostring ());//The key in the map is not duplicated, if you insert two key values of the same record,//Then the inserted record will overwrite the first inserted record Map.put (key, key.tostring () + "0");}} public static void output (map map) {if (map! = null) {Object key = null;object value = null;//uses the iterator to traverse the Map key, based on the key value iterator it = Map.keyset (). iterator (); while (It.hasnext ()) {key = It.next (); value = Map.get (key); System.out.println ("key:" + key + "; Value: "+ value";} Or use an iterator to traverse the record of the map Map.EntryMap.Entry Entry = Null;it = Map.entryset (). iterator (); while (It.hasnext ()) {// A map.entry represents a record Entry = (map.entry) it.next ();//The key and value of the record can be obtained by Entry//System.out.println ("key:" + entry.getkey () + "; Value: "+//entry.getvalue ());}}} public static BooleAn ContainsKey (map map, Object key) {if (map! = null) {return Map.containskey (key);} return false;} public static Boolean Containsvalue (map map, Object value) {if (map! = null) {return map.containsvalue (value);} return false;} public static void Testhashmap () {Map myMap = new HashMap (); init (MYMAP);//HashMap key can be nullmymap.put (null, "ddd");//Hash The value of map can be nullmymap.put ("AAA", null); output (MYMAP);} public static void Testhashtable () {Map myMap = new Hashtable (); init (MYMAP);//Hashtable key cannot be null//mymap.put (null, "DDD" )///Hashtable value cannot be null//mymap.put ("AAA", null); output (MYMAP);} public static void Testlinkedhashmap () {Map myMap = new Linkedhashmap (); init (MYMAP);//Linkedhashmap key can be nullmymap.put ( NULL, "DDD");//The value of Linkedhashmap can be Nullmymap.put ("AAA", null); output (MYMAP);} public static void Testtreemap () {Map myMap = new TreeMap (); init (MYMAP);//TreeMap key cannot be null//mymap.put (null, "ddd");/Tr The value of Eemap cannot be null//mymap.put ("AAA", null); output (MYMAP);} public static void Main (string[] args) {System.out.println ("Using HashMap"); Maptester.testhashmap (); System.out.println ("Using Hashtable"); Maptester.testhashtable (); System.out.println ("Using Linkedhashmap"); Maptester.testlinkedhashmap (); System.out.println ("Using TreeMap"); Maptester.testtreemap (); Map MyMap = new HashMap (); Maptester.init (MYMAP); SYSTEM.OUT.PRINTLN ("New initialization of a Map:mymap"); Maptester.output (MYMAP);//emptying mapmymap.clear ();  System.out.println ("Will mymap clear, mymap empty?" "+ mymap.isempty ()); Maptester.output (MYMAP) mymap.put ("AAA", "AAAA") mymap.put ("BBB", "bbbb");//Determine if the map contains a key or a value System.out.println ("  Mymap contains key AAA? "+ Maptester.containskey (MyMap," AAA "));  System.out.println ("Mymap contains value aaaa?") "+ Maptester.containsvalue (myMap," AAAA "));//delete the record in map Mymap.remove (" AAA ") according to the key;  System.out.println ("Remove key AAA, Mymap contains key AAA?") "+ Maptester.containskey (MyMap," AAA "))///Get Map number of records System.out.println (" MyMap contains the number of records: "+ mymap.size ());}}


Attached: Four Ways to map traversal:

public static void Main (string[] args) {map<string, string> Map = new hashmap<string, string> ();  Map.put ("1", "value1");  Map.put ("2", "value2");    Map.put ("3", "Value3");  First: Universally used, two times value System.out.println ("Traverse key and value by Map.keyset");  For (String Key:map.keySet ()) {System.out.println ("key=" + key + "and value=" + map.get (key));  }//second type of SYSTEM.OUT.PRINTLN ("Traverse key and value by Map.entryset using iterator");  Iterator<map.entry<string, string>> it = Map.entryset (). Iterator ();   while (It.hasnext ()) {map.entry<string, string> Entry = It.next ();  System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());  }//Third type: recommended, especially when the capacity is large System.out.println ("Traverse key and value through Map.entryset"); For (map.entry<string, string> entry:map.entrySet ()) {System.out.println ("key=" + entry.getkey () + "and value  = "+ Entry.getvalue ());  }//Fourth type SYSTEM.OUT.PRINTLN ("Traverse all the value through Map.values (), but cannot traverse key"); For (String v:map.values ()) {SystEm.out.println ("value=" + V); } }

3. Other Features

*List,set,map holds objects as Object type.

*collection, List, Set, and map are interfaces and cannot be instantiated.

ArrayList, vectors, HashTable, and HashMap are inherited from them, and these can be instantiated.

The *vector container knows exactly what type of object it holds. Vectors do not perform boundary checks.

Third, collections

Collections is a helper class for the collection class. Provides a series of static methods for searching, sorting, threading, and so on for various collections.

A class--arrays equivalent to a similar operation on an array.

For example, Collections.max (Collection coll); Take the largest element in the Coll.

Collections.sort (list list); Sort elements in List

Iv. How to choose?

1, the difference between the container class and the array, playable

* The container class can only hold object references (pointers to objects), rather than copy the object information to a position in a sequence.

* Once the object is placed in the container, the object's type information is lost.

2.

* In various lists, the best practice is to use ArrayList as the default choice. when inserting and deleting frequently, use LinkedList ();

Vector is always slower than ArrayList, so try to avoid it.

* In various sets, hashset is usually better than treeset (INSERT, find). Use TreeSet only if you need to produce a sorted sequence.

The only reason for the existence of TreeSet: the ability to maintain the ordering state of its elements.

* In a variety of maps

The HashMap is used for quick lookups.

* When the number of elements is fixed, use array, because array efficiency is the highest.

Conclusion: The most commonly used is arraylist,hashset,hashmap,array. Also, we will find a pattern, which is sorted by treexxx.

Attention:

1. Collection does not have a get () method to get an element. Elements can only be traversed by iterator ().

2. Set and collection have identical interfaces.

3, List, you can use the Get () method to remove one element at a time. Use numbers to select one of a bunch of objects, get (0) .... (Add/get)

4, generally use ArrayList. use LinkedList to construct stack stacks, queue queues.

5, map with put (K,V)/get (k), you can also use ContainsKey ()/containsvalue () to check if it contains a key/value.

HashMap will use the object's hashcode to quickly find the key.

* Hashing

The hash code is the transformation of the object's information into a unique int value, stored in an array.

We all know that the array lookup speed is the fastest in all storage structures. So, you can speed up lookups.

When a collision occurs, let the array point to multiple values. That is, the array generates a table of cassia at each location.

6, the element in the map, you can extract the key sequence, the value sequence alone.

Use Keyset () to extract the key sequence and generate a set for all keys in the map.

Use values () to extract the value sequence and generate a collection for all values in the map.

Why a build set, a Build collection? That's because key is always unique and value allows repetition

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.