Hierarchy and usage rules grooming for the [Java] collection Framework

Source: Internet
Author: User

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.

Overview
    • What is a framework?
        

Collection of class libraries

    • What is a collection?

Container for storing data

    • What is a set frame for?

A unified architecture for representing and manipulating

A collection framework consists of two parts: a class and a part interface (a class that is used to standardize similar functions)

Main structure diagram:

 

The Java Collection Toolkit, located under the Java.util package, contains a number of common data structures, such as arrays, lists, stacks, queues, collections, hash tables, and so on.
  
The Java Collection framework focuses on the use of list lists, set sets, map mappings, iterators (Iterator, enumeration), tool classes (Arrays, collections).

Collection

Collection is a highly abstracted interface of the list, set, and so on, which contains the basic operations of these collections, and all classes that implement the interface and its sub-interfaces can apply the clone () method and be a serialized class.
   
The main implementation of the relational hierarchy diagram:

    

Common Methods of collection:

    • Add to
      Boolean Add (e e);
      Boolean AddAll (collection<> c)
    • Delete
      Boolean remove (e e);
      Boolean RemoveAll (collection<> c);
      void Clear ();
    • Judge
      Boolean contains (Object o)
      Boolean containsall (collection<> c)
      Boolean isemply ();
    • Get
      int size ();
      Iterator Iterator ();
    • Other
      Boolean Retainall (Collection coll);
      Object[] ToArray ();
List

The list interface usually represents a listing that can randomly access the contained elements, which are ordered and can be added and deleted anywhere, regardless of the number of times the element is accessed and the elements are positioned unchanged, allowing repeating elements.
  
Using iterator to implement one-way traversal, you can also use Listiterator to implement bidirectional traversal.

List-specific common methods:

    • Add to
      void Add (index,element);
      void Add (index,collection);
    • Delete
      Object Remove (index);
    • Get
      Object get (index);
      int IndexOf (object);
      int LastIndexOf (object);
      Last Sublist (from,to);
    • Modify
      Object set (index,element);
LinkedList

Internal is a linked list data structure, random access is very slow , and Delete operations quickly , do not consume redundant resources, allow null elements , non-thread-safe . If multiple threads access a list at the same time, you must implement access synchronization yourself.

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

The interior is an array of data structures, and the elements are stored sequentially. When the new element changes the list size, a new array is created internally, and all data is copied to the new array before the element is added. random access quickly , Delete non-kinsoku elements slow, new elements slow and cost resources. More suitable for the case of no frequent additions and deletions, can grow the array, 50% extended. Less efficient than arrays, consider using arrays, non-thread safe If you do not need a mutable array.

Vector

Another kind of ArrayList, with ArrayList characteristics. All methods are thread-safe (two-edged swords, and the main difference between ArrayList) is less efficient than ArrayList.

Stack

The data structure of LIFO, stack inherits from Vector, is also synchronous .

Set

Typically represents a collection in which the methods in the interface are consistent with the collection. is a collection that does not allow repeating elements, can have an empty element , cannot randomly access the contained elements, can only implement one-way traversal with iterator, set** out of sync * *.

HashSet

The internal data structure is a hash table (HASHMAP), the elements are unordered , and the order of iterating over the elements is different from the order in which they were added. Multiple iterations of access, the order of elements may be different, non-thread-safe .

Linkedhashset

Based on the set implementation of HashMap and linked lists, the order of iterated access elements is the same as the order in which they are joined, multiple iterations are accessed, and the order of the elements is unchanged.

SortedSet

All elements that join the SortedSet must implement the comparable interface, and the elements are ordered .

TreeSet

Based on the TreeMap implementation of SortedSet, you can sort the elements in the set collection, sort the elements in ascending order, and not thread safe .
 
Two kinds of sorting methods:

    • To make the element own the comparison function, the element needs to implement the Compareable method to cover the CompareTo method.
    • Let the collection itself have a comparison function, define a class to implement the comparator interface, overriding the Compare method.
Map

is a mapping interface, 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.
  
Abstract class Abstractmap through the adapter mode to achieve most of the map interface functions, TreeMap, HashMap, Weakhashmap and other implementation classes are inherited abstractmap to achieve, But the infrequently used Hashtable directly implements the map interface.

To implement a relational hierarchy diagram:

 

Common methods in Map:

    • Add to
      Value put (Key,value): Returns the value associated with the previous key and returns null if none
    • Delete
      void Clear (): Clears the Map collection.
      Value Remove (key): Deletes this key value pair according to the specified key
    • Judge
      Boolean Containkey (Key)
      Boolean Containvalue (Value)
      Boolean isEmpty ();
    • Get
      Value get (key), which is obtained by key, if no key is returned NULL, you can certainly determine whether the specified key is included by returning NULL
      int size () Gets the number of key-value pairs.

method to remove all values from the map collection:

    • By using the keyset method, we get the set set of all the keys in the map, get each key through the set iterator, and then take the corresponding value for each key by the Get method of the map collection.
        Map Map = NewLinkedhashmap ();Map.Put"1","First Number");Map.Put"2","second Number");Map.Put"3","Number three"); for (Object obj:Map.KeySet ()) {StringKey=(String) obj;StringValue=(String)Map.Get (key); }
    • The EntrySet method of the Map collection can also take out all the key-value pairs in the Map collection, return the Map.entry object, and then remove the corresponding key and value by Map.entry the Getkey and GetValue methods of the object.
        Map Map = NewLinkedhashmap ();Map.Put"1","One");Map.Put"2","both");Map.Put"3","three"); for (Object obj:Map.EntrySet ()) {Entry Entry=(Entry) obj;StringKey=(String) entry.GetKey ();StringValue=(String) entry.GetValue (); }
    • Traverse keyset or entryset through iterator
        Map Map = NewHashMap ();Map.Put"1","One");Map.Put"2","both");Map.Put"3","three");Set Set = Map.KeySet (); Iterator it= Set.Iterator (); while(It.Hasnext ()) {StringKey=(String) it.Next ();StringValue=(String)Map.Get (key); }
        Map Map = NewHashMap ();Map.Put"1","One");Map.Put"2","both");Map.Put"3","three");Set Set = Map.EntrySet (); Iterator it= Set.Iterator (); while(It.Hasnext ()) {Entry Entry=(Entry) it.Next ();StringKey=(String) entry.GetKey ();StringValue=(String) entry.GetValue (); }
Hashtable

The object used as a key must implement the Hashcode (), Equals () method, meaning that only object and its subclasses can be used as keys, Hashtable inherit from the dictionary dictionary, and implement the map interface. keys, values cannot be empty objects , multiple accesses, the order of the mapped elements is the same , thread safety .

Properties

Inherited from Hashtable, both the key and the value are strings .

HashMap

The internal structure is a hash table, the keys and values can be empty objects, do not guarantee the order of the mappings, multiple accesses, the order of the mapped elements may be different, non-thread-safe .

Linkedhashmap

Inherited from HashMap, multiple accesses, the order of mapping elements is the same , performance is worse than HashMap.

Weakhashmap

When a key is no longer working properly, the garbage collector removes it, even if there is a mapping relationship that is not thread safe .

SortedMap

Keys are sorted in ascending order, and all keys must implement the comparable interface.

TreeMap

The internal structure is a two-fork tree (based on a red-black tree implementation), and the keys in the map collection can be sorted in different steps .

Iterator

Iterator is an iterator that iterates through the collection (it cannot traverse the map and is used only to traverse collection), and the collection implementation class implements the iterator () function, which returns a iterator object.
  
Listiterator is designed to traverse the list.
While enumeration is JDK1.0, the function is the same as iterator, but its function is less than iterator, it can only be used in Hashtable, vector and stack.

Arrays and collections are the two tool classes used to manipulate arrays and collections.

Tips for use
    • Needs to be unique with Set
      And you need to specify the order: TreeSet
      Not required: HashSet
                 
      Get the same order of storage: Linkedhashset
             
    • Do not need to use list only
      Need frequent and delete action: LinkedList
      Not required: ArrayList
                
    • If you are involved in stacks, queues and other operations, you should consider using list;

    • For the need to quickly insert, delete elements, should use LinkedList;

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

    • If multiple threads might manipulate 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. Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to replace ArrayList with LinkedList later, the client code does not have to change, which is for abstract programming.

Hierarchy and usage rules grooming for the [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.