Java Collection Framework Knowledge Summary

Source: Internet
Author: User
Tags comparable set set

Two major systems: Collection,map

First, Collection:

List Interface:

List: The objects are all in order (three ways to traverse)
Arraylist,linkedlist,vertor

ArrayList: An array of dynamically variable lengths is essentially maintained in ArrayList.

Common methods:
Increment: Add (4) Object position + object collection + location.
Delete: Remove (2) Subscript Delete the object and delete the object directly.
Change: Set (1) Subscript object.
Check: Get () Subscript object, IndexOf () object to subscript.

Contains () must be the same object to return True iterator () size ().


LinkedList: In essence LinkedList is maintained in a dynamic variable-length doubly linked list

 Common methods:
Increment: Add (4) Object position, object collection position, collection +2 (object) added: AddFirst () AddLast ().
Delete: Remove (2) Subscript Delete object, direct Delete Object +2 (object) added: Removefirst () Removelast ().
Change: Set (1) Subscript Object
Check: Get () Subscript object IndexOf () object is subscript +2 (object) NEW: GetFirst () GetLast ().

Contains () iterator () size ().


Vertor: Thread-safe, very inefficient execution

Common methods:
Increment: Add (4) Object position, object collection position, collection addelement (object) insertelement (object).
Delete: Remove (2) Subscript Delete object, directly Delete object Removeelement (object) removeallelment ().
Change: Set (1) Subscript, Object Setelementat (object, subscript).
Check: Get () Subscript object IndexOf () object.

Contains () iterator () size ().

Iterator (): Hasnext () Determines if there is no next element.
Next () gets the next element.
Remove () Removes the element from the iterator.

Set interface:
Duplicate methods are not allowed, allowing for a null value that has no sequential index (traversed by the enhanced for loop and iteration), so it cannot be checked and cannot be changed.
To deposit the set, you must override the Equals () and Hashcode () methods (string has been overridden), both of which are true to indicate equality, compared to the content.
In fact, a equals () can be, but when the amount of data deposited large, one by one is very inefficient, adding hashcode, is to judge not the same object.
the same object cannot be judged by hashcode ().

  Because all the objects that have been deposited are stored in a table, the comparison is very efficient.
If it already exists, it can no longer be added to it (and the map is later overwritten).
HashSet:
The internal maintenance is an instance of HashMap, which is a collection of keys.
The expression of the element is unordered, but once the element is added, the position of the element is fixed (that is, no matter how many times you run it, the order of the display is the same), and then add a new element without affecting the position of the preceding element, assigning a position to the added element, as long as the previous element position is not disturbed. The position of the previous element will no longer change.

Common methods:
Increment: Add (object).
Delete: Clear () Removes all objects, remove (object).
Change: No, no subscript.
Check: Except to traverse out all, no, because there is no subscript.

Contains () returns True iterator () size () in the same content.


Linkedhashset:
HashSet subclass, only four new constructors, no other new method, internal maintenance is an instance of Linkedhashmap, is a doubly linked list structure.
The elements are stored in the same order as the iteration order (in order).
Common methods with HashSet.


TreeSet:

Make sure that the element is in a sorted state, with the underlying tree structure. Use it to extract ordered sequences from the set.

Two sort methods: natural sort and custom sort, by default natural sort.
Natural sort: The Comparato (object) method of the collection element is called to compare the size relationship between elements, and then the collection is sorted in ascending order (implementing the comparable interface).
Custom ordering: Through the comparator (comparator) interface, you need to rewrite the Compara (object, object), to achieve custom ordering, the comparator instance needs to be passed as a parameter to the TreeSet constructor.
In order to put elements into TreeSet, the comparable interface must be implemented, and the Comparato method must be implemented.
or inherit the comparator interface, and then override the Compara method.
First () Last () lower (object) Heigher (object) other view methods.


Two, map collection: Maintaining associativity for key-value pairs

 key,value must be reference type data
  Key cannot be repeated (after overwriting first) and saved in the set set (because the elements inside the set set cannot be duplicated, you must also override the Equals and Hashcode () methods), often with string, because all have implemented
  put (key, Value) remove (key) Putall (map map) Clear () clears all. (basically all through set, that is, the key, uniqueness).
  Get a collection of keys:
    set<> set= map.keyset ();iterator<> it= Set.iterator (); Get (key) iterator.
  Get a collection of value:
    Collection values () iterator, enhanced for all.
 entry Collection:
   Set<Entry<,>> entrys = Map.entryset ();
   for (entry<string,string> Entry:entrys) iterator, enhanced for all can be
   get (key) ContainsKey (key) con Tainsvalue (value) size isEmpty () equals () is of course content.

HashMap:
allows the value of key and value to be null.
behaves like an unordered comparison of key equality and set.
Linkedhashmap: Subclasses, ordered (equivalent to HashSet and Linkedhashset above) are only a little slower than HashMap. The iteration is accessed faster because it uses the list to maintain the internal order.

TREEMAP:

Ordered. Based on the implementation of red-black tree data structure. When you look at key or key-value pairs, they are sorted (the order is determined by comparabel or comparator). TreeMap is the only map with the Submap () method, which can return a subtree.
HashTable:

Oldest, does not allow the key and value to be null

Properties:
is a subclass of Hashtable that is used to manipulate the properties of a file.
The file attribute must be key_value, must be a string, access data with put (Key,value), get (key).

Collections:
Collection Operation class
  Sort:
Collections.reverse (list) reverse order
Collections.shuffle () random
Collections.sort () Natural order Ascending
Collections.swap (object, position, position) Exchange
  Find:
Max ()
MIN () Frequency (collections, object);
Copy (target list,srclist)
Collections.repalceall (List,old object, new Object)

Synchronizedxxx ();
Synchronizedlist (list)

Summary:  

1. Thread-Safe is vertor and Hashtable.
2. List: Allow duplicates, all in order (Null allowed).
3.set:hashset unordered expression (a null), in which HashSet subclasses linkedhashset orderly, treeset orderly.
4.map:hashmap unordered behavior (once null), where HashMap subclasses linkedhashmap orderly, treemap orderly, Hashtable unordered (cannot be null).

5.ArrayList: The query efficiency is high, the deletion efficiency is low.
6.LinkedList: The query efficiency is low, and the efficiency is high.
7.Vertor: Very low execution efficiency.

8.HashSet: Good to delete query performance.
9.LinkedHashSet: The query efficiency is low, the insertion efficiency is lower than hashset.

The 10.Map object is higher than list. Because the map requires an object key in addition to value, it increases the capacity of the map.

Hashset,hashmap elements are unordered, and their subclasses are orderly, doubly linked lists, very similar, because the only constraint in HashMap is key, and key is precisely HashMap maintained
Both 12.TreeSet and treemap are orderly, and the two are very similar.

13. If map knows that key,list knows index, its performance is not much different in 1 million data.

14.List saves objects in the order in which they are entered, without sorting or editing. Set accepts only once for each object and uses its own internal ordering method (usually, you are only concerned about whether an element belongs to Set, but not the order of it, or you should use list). Map also saves one copy of each element, but this is based on the "key", and the map has a built-in sort, so it doesn't care about the order in which the elements are added. If the order of adding elements is important to you, you should use Linkedhashset or Linkedhashmap.

15.HashMap is a quick query using the object's Hashcode (). This method can significantly improve performance.


To give a simple example:

Import Java.util.collection;import java.util.hashmap;import Java.util.iterator;import Java.util.Map;import                  Java.util.map.entry;import Java.util.set;public class Testhashmap {public static void main (string[] args) {        map<string, string> map = new hashmap<string, string> ();        Put () adds an element (Key-value) Map.put ("5", "ddd") to the map;        Map.put ("1", "AAA");        Map.put ("2", "BBB");        Map.put ("3", "CCC");        Map.put ("4", "CCC");        HashMap traversal set<string> keys = Map.keyset ();        Iterator<string> it = Keys.iterator ();        Iterator<string> it = Map.keyset (). Iterator ();        System.out.println ("-----------HashMap traversal method one-------------");        System.out.println ("-----------map.keyset ()-------------");            while (It.hasnext ()) {String key = It.next ();        Get returns the value System.out.println (key + ":" + map.get (key)) corresponding to the specified key. } collection<string> C2=map.values ();        for (String str:c2) {System.out.println (str);         } set<entry<string,string>> Entrys = Map.entryset ();         System.out.println ("-----------HashMap traversal method three-------------");     System.out.println ("-----------map.entryset ()-------------");        for (entry<string,string> Entry:entrys) {System.out.println (Entry.getkey () + ":" + entry.getvalue ());         } System.out.println ("-------------");        The Remove method removes the element corresponding to the specified key and returns the corresponding value System.out.println (Map.Remove ("4"));        If key does not exist, returns NULL, the removal operation is invalid SYSTEM.OUT.PRINTLN (Map.Remove ("9"));         System.out.println (-------------after "-----------Map.Remove ()");         it = Map.keyset (). iterator ();         while (It.hasnext ()) {String key = It.next ();         Get returns the value System.out.println (key + ":" + map.get (key)) corresponding to the specified key.         }////Determine if the specified key System.out.println (Map.containskey ("1") is present in the map; SYstem.out.println (Map.containskey (New String ("1"));         Determine if the specified value System.out.println (Map.containsvalue ("AAA") exists in the map;    System.out.println (Map.containsvalue (New String ("AAA"))); }}

Summarizes only the collections that are commonly used.

Java Collection Framework Knowledge Summary

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.