Java Collection 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 () 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:
        Do not allow duplicate methods, allow a null value, no sequential index (traversed by enhanced for loop and iteration), So I can't find it, I can't change it.
  to deposit set, you must override the Equals () and Hashcode () methods (string has been overridden). Both return values are true to indicate equality, compared to the content.
  actually a equals () is OK, but when the amount of data is large, the The comparison is very inefficient, To join Hashcode is to judge not the same object.
  hashcode () cannot be judged to be the same object.

  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 element's transition is unordered, but once the element is added, the position of the element is fixed (that is, the order of the display is the same regardless of how many times you run it), and then the new element is added and the position is rearranged.

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 () iterator () size ().


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 the sorted state the bottom layer is a 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.


Ii. Map Collection: Maintaining the relevance of "key-value pairs"

Key,value must both 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),always use string because it is already implemented
put (key,value) remove (key) Putall (map map) Clear () clears all. (basically all through set, that is, the key, uniqueness).
get the collection of keys:  
set<> set= map.keyset ();iterator<> it=set.iterator (); Get (key) iterator.
gets the collection of value:  
the Collection values () iterator, enhanced for, is available.
Entry Collection:  
set<entry<,>> Entrys = Map.entryset ();
for (entry<string,string> Entry:entrys) iterators, the enhanced for can be
get (Key) ContainsKey (key) Containsvalue (value) size isEmpty () equals () of course it's the content.

HashMap:
allows the value of key and value to be null.
the performance is unordered compared to 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:
Span style= "FONT-SIZE:16PX;" > is a subclass of Hashtable that is used to manipulate the properties of a file.

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:

Importjava.util.Collection;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportJava.util.Set; Public classTesthashmap { Public Static voidMain (string[] args) {Map<string, string> map =NewHashmap<string, string>(); //put () adds an element to the map (key-value)Map.put ("5", "DDD"); Map.put ("1", "AAA"); Map.put ("2", "BBB"); Map.put ("3", "CCC"); Map.put ("4", "CCC"); //traversal of the HashMapset<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 corresponding to the specified keySYSTEM.OUT.PRINTLN (key + ":" +Map.get (key)); } Collection<String> c2=map.values ();  for(String str:c2) {System.out.println (str); } Set<Entry<String,String>> Entrys =Map.entryset (); System.out.println ("-----------The traversal method of HashMap 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 valueSystem.out.println (Map.Remove ("4")); // //If key does not exist, NULL is returned and the remove operation is invalidSystem.out.println (Map.Remove ("9")); System.out.println ("-----------Map.Remove () after-------------"); It=Map.keyset (). iterator ();  while(It.hasnext ()) {String key=It.next (); //get returns the value corresponding to the specified keySYSTEM.OUT.PRINTLN (key + ":" +Map.get (key)); }        //         //determine if the specified key exists in the mapSystem.out.println (Map.containskey ("1")); System.out.println (Map.containskey (NewString ("1"))); //determine if the specified value exists in the mapSystem.out.println (Map.containsvalue ("AAA")); System.out.println (Map.containsvalue (NewString ("AAA"))); }}

Summarizes only the collections that are commonly used.

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