Collection Summary-1

Source: Internet
Author: User
Tags comparable list of attributes sorts

Learning methods, do not because of a small problem caused by large technical learning.
The way to learn is not to listen, but to do, and to persist. You have to hit the code to save time.

One, Collection interface (sub-interface: Set, List)
Common methods of ★collection systems (more important than proprietary methods)
(1) "Add" action
Boolean Add (Object o): Add an object to the collection
Boolean AddAll (Collection C): Add all elements in C to the collection
(2) "Judging" action
Boolean contains (object O): Determines whether the collection contains objects O
Boolean containsall (Collection C): Determines whether the collection contains all elements in set C
Boolean IsEmpty (): Determines whether there are any elements in the collection
(3) "Delete" action
Boolean remove (Object O): If there are objects in the collection that match O, delete the object o
★void RemoveAll (Collection C): Remove the "contains" element from the collection in the collection C
void Clear (): Removes all elements in the collection, as with remove, changing the length of the collection
★void Retainall (Collection c): Removes the "not contained" element in collection C from the collection (takes intersection)
(4) "Get" action
★iterator Iterator (): Returns an iterator to access the individual elements in the collection
int size (): Returns the number of elements in the current collection (as with map, using the size method)
(5) converted to an object array (for the purpose of preventing additions or deletions to the collection after being converted to an array)
★object[] ToArray (): Returns an array containing all the elements of the collection
<T> t[] ToArray (t[] a): This method needs to pass in an array object, and if the length of this array is less than the size of the collection, the method creates an array of the same type, length, and collection size, and stores the elements in the collection sequentially If the length is greater than the size of the collection, an array of the same length is created and the other location is null.

1, List interface (inherit collection, element allows repetition, order)
★ (1) "Basic" operation, List inherits all the methods of collection and provides a unique method based on "location"
Object get (int index): Returns the element at the specified position in the list
int indexOf (Object o): Returns the position of the first occurrence of element O, otherwise returns-1
int lastIndexOf (Object o): Returns the position of the last occurrence of element O, otherwise returns-1
Object Remove (int index): Deletes the element at the specified position
Object Set (int index, OBJECT element): replaces the specified position element and returns the old element
List sublist (int fromIndex, int toindex) returns the specified range Subsequence, containing the first not containing the tail
(2) "Iterator" action (also with iterator method that returns iterator)
★listiterator listiterator (): Returns a list iterator to access the elements in the list
Listiterator listiterator (int index): Returns an iterator that accesses the elements in the list starting at the specified position

1.1, ArrayList class (Implementation of the list interface, query fast, can be understood as "variable size array")
Allows the inclusion of a NULL element to manipulate the size of the array used internally to store the list, with a unique method to understand it.
(1) void ensurecapacity (int mincapacity): Increases the ArrayList object's capacity Mincapacity
void TrimToSize (): Defragment (Decrease) ArrayList object capacity as List current size
(2) ArrayList initialization can not specify capacity, if created in New ArrayList (), the initial capacity is 10, when an element is added to ArrayList, the container capacity adjustment, if the capacity is not enough, is added to the original 1.5 times times plus 1, then the element is added to the container, which increases by 0.5 times times the original capacity.

1.2, LinkedList Class (Implement list interface, delete and insert speed, can be understood as "doubly linked list")
(1) LinkedList is implemented by a doubly linked list, similar to the stack (advanced post-out, FILO) or queue (FIFO) data structure, suitable for the insertion and deletion of elements.
★ (2) The LinkedList class adds some methods for working with the "both ends of the list"
void AddFirst (Object o): Adds an object o to the beginning of the list
void AddLast (Object o): Adds an object o to the end of the list

Object GetFirst (): Gets the beginning element, if the linked list is empty, throws an exception
Object getlast (): Gets the end element, if the linked list is empty, throws an exception
Object Peekfirst (); Gets the element at the beginning, if the linked list is empty, returns null
Object peeklast (): Gets the end element if the linked list is empty, returns null

Object Removefirst (): Gets and removes if the linked list is empty, throws an exception
Object removelast (): Gets and removes if the linked list is empty, throws an exception
Object Pollfirst (); Gets and removes if the linked list is empty, returns null
Object polllast (); Gets and removes if the linked list is empty, returns null
(3) Advantages and disadvantages of ArrayList and LinkedList
ArrayList: is implemented in arrays (similar to a series), suitable for random access, "read" fast, insert and delete slow (because the insertion and deletion to move all the elements behind).
LinkedList: Two-way linked list, "Delete and insert" fast, read slower, because it reads from the head to tail or from the tail to find elements. If you want to frequently add and remove elements from the middle of the list, and as long as the sequential access list element, then the LinkedList implementation is better.

2, Vector Class (implement collection interface, applied to multi-threading, adding and deleting changes are very slow, not recommended)
(1) function, structure and so on are almost the same as ArrayList, but add, delete, read, set are based on thread synchronization.
(2) Vector initialization capacity can be set, if created with the new vector (), then the initial capacity of 10, more than the capacity of twice times the capacity increase.
(3) The iterator in the vector can be either iterator or "enumeration"

//*****************************************************************************************
3, Set interface (inherit collection, element is not allowed to repeat (core characteristics), unordered (can also be ordered))
The method in the set interface is consistent with the collection

3.1, HashSet class (unordered, implement set interface, internal data structure is HASHMAP, can be understood as "set" in mathematics)
★ (1) HashSet How to guarantee the uniqueness of the collection element? The
is based on the hashcode of the object and the Equals method to determine the uniqueness of the object.
If the object's Hashcode value is different, it is stored directly in the hash table without judging the Equals method.
If the hashcode value of the object is the same, determine again whether the object's Equals method is true. The
If true, is considered the same element and does not exist. If False, it is stored as a different element.
(2) Generally, if a defined class produces many objects, such as people, students, and books, it is usually necessary to override the Equals and Hashcode methods to establish the basis for judging whether the objects of the respective classes are the same.
such as two objects, (ab,1) and (ab,1), if directly with the Hashcode method of object (different objects return different integers), then (ab,1) and (ab,1) The hashcode value is not consistent, equals (= =) result is also false.
(3) Note: The most commonly used string class has overridden both methods (StringBuilder, StringBuffer not)
3.1.1, Linkedhashset class (Ordered, inherited HashSet, can be understood as "in mathematics" Once function ")
differs from HashSet in order, and its iterators access each element sequentially in the order in which the elements are inserted

3.2, TreeSet class (ordered, implement set and SortedSet interface, internal data structure is two fork tree (TREEMAP))
★ (1) Two constructors
TreeSet () constructs a new empty set, the set Sort according to the natural order of their elements, note that in this way the TreeSet is constructed, and the custom object must override the CompareTo method of the comparable interface.
TreeSet (Comparator C): Constructs an empty TreeSet, which is sorted according to the specified Comparer object C
★ (2) TreeSet implementation of ordering elements
Way One: Let the elements themselves have a comparison function, element to implement the CompareTo method of the comparable interface
(note that the string class and the basic type wrapper class have overridden this method, all sorted in natural order)
Mode two: Let the collection itself have a comparison function, define a class implementation comparator interface, Overrides the Compare method, passing the class object as a parameter to the constructor of the TreeSet collection.
(3) If both methods exist at the same time, the comparison function of the set itself will be the same

//*****************************************************************************************
//*********** The
Two, the Map interface (and collection are all top-level interfaces, Similar to the "function" in mathematics (x is unique, y can be repeated))
Features: Map to add a pair of elements at a time, Collection add an element at a time, map is also known as a double-column collection, Collection is also known as a single-row collection; The map stores key-value pairs You must guarantee the uniqueness of the key.
★map System Next Common commonality method:
1, Add.
★value put (key,value): Returns the value associated with the previous key, if NULL is not returned.
2, delete.
Void Clear (): Empties the Map collection
★value Remove (key): If a mapping of a key exists, it is removed from this mapping and returns the value of the previously associated key in this map, or null if the mapping does not contain a mapping of the key
3, judging.
Boolean ContainsKey (Key):
Boolean Containsvalue (value):
Boolean isEmpty ();
4, get.
★value Get (key): Gets the value by key, or returns NULL if no key is used to determine whether the specified key
int size (): Gets the number of key-value pairs
★ 5, traversal operation.
set<k> KeySet (): Returns the Set view of the key contained in this map
collection<v> values (): Returns the Collection view of the values contained in this map
Set<map.entry<k,v>> EntrySet (): Returns the Set view of the mapping relationship contained in this map

2.1. HashMap class: Unordered, internal structure is a hash table, key cannot be duplicated, allow key or value to be null.
★ As with HashSet, using HashMap generally requires overriding its hashcode () and Equals () methods on the "Key class"
2.1.1, Linkedhashmap class: Inherit hashmap, add keyword/value pairs into the link hash map image in order of insertion. Like Linkedhashset, a double-linked list is also used inside the linkedhashmap.

2.2, TreeMap class: Ordered, the internal structure is a two-fork tree, you can sort the "keys" in the Map collection.
TreeMap implements the map and the SortedMap interface, similar to the TreeSet class, the key to the element that is added to the TreeMap class must implement the comparable interface, otherwise it must provide an implementation of the comparator interface to its constructor
★ (1) Construction method
TreeMap (): Constructs a new, empty tree map using the natural order of the keys
TreeMap (Comparator C): Constructs a tree image that uses the comparer C to sort the keywords
TreeMap (SortedMap s): Constructs a new tree map with the same mapping relationship and the same sort order as the specified ordered map s
(2) Comparator Comparator (): Returns the comparer used when sorting "keywords" and returns null if the keyword is compared using the CompareTo () method of the comparable interface)
(3) Advantages and disadvantages of HashMap and TreeMap
It is better to insert, delete, and position elements frequently in the map HashMap.
But if you want to traverse the key in natural order or in a custom order, TreeMap is better.

2.3, Hashtable class: The internal structure is a hash table, is synchronous. Null is not allowed as a key, and Null is used as a value.
2.3.1, Properties Class: The direct sub-class of Hashtable, is synchronous. The
Properties file is a configuration file (INI, XML file also) with a file type of *.properties and formatted as a text file. The contents of the file are the "key = value" format, and the keys and values are strings, annotated with a "#" tag. Often combined with IO technology, the data in the collection can be saved to the stream (store) or fetched from the stream (load).
1.getProperty (key), Get value
2.setProperty (key, value) by key, and indirectly call Hashtable's Put method to set the key-value pair.
★3.load (Inputstream/reader), reading the list of attributes (key and element pairs)
★4.store (Outputstream/writer, String) from the input stream, writing key-value pairs to the specified output stream
5.list (Printstream/printwriter) in the associated file, outputting the list of attributes to the specified output stream. This method is useful for debugging.
6.stringPropertyNames (), which returns the set set of keys in the property list, including the keys in the default properties list


//*****************************************************************************************
//*****************************************************************************************
Three, iterator interface (collection can generate this interface object)
★ (1) "Traversal" operation
Boolean Hasnext (): Determines whether the next accessible element exists
Object Next (): Returns the next element to be accessed. Throws an exception if none is thrown
(2) void Remove (): Deletes the object returned from the last access. This method must be executed immediately after the access of an element. If the collection has been modified since the last visit, the method throws IllegalStateException

2.1, Listiterator Interface (iterator sub-interface, list can generate this interface object)
(1) "Forward traversal"
Boolean Hasnext (): Traverse list in forward direction
Object Next (): Returns the next element
int Nextindex (): Returns the index of the element that will be returned the next time the next method is called
(2) "Reverse traversal"
Boolean hasprevious (): Traversing the list in reverse
Object Previous (): Returns the previous object
int Previousindex (): Returns the index of the element that will be returned the next time the previous method is called
★ (3) "Change over time"
void Add (Object O): Adds an object o to the front of the current position
void set (Object O): The previous element accessed using the object o instead of the next or previous method
void Remove () removes the last element returned by next or previous from the list

X. Enumeration interface (provides only the ability to traverse Vector and Hashtable type collection elements)
This interface is similar to the Iterator interface, but does not support the removal of elements, and the new implementation should take precedence over the use of the Iterator interface. Often used to assign an "input stream" to Sequenceinputstream.
(1) Boolean hasmoreelements () tests whether this enumeration contains more elements.
E nextelement () returns the next element of this enumeration.
(2) Note that the static method of the Collection tool class <T> Enumeration<t> enumeration (COLLECTION&LT;T&GT;C) can return an enumeration on a specified collection. This is a preferred way to obtain an object when it needs to be enumerated.
(3) In addition, the PropertyNames method of the subclass properties of Hashtable can return all the health enumerations.
//*****************************************************************************************
//*****************************************************************************************
Four, comparable interface (let the class itself has the sort function)
(1) This interface forces the overall ordering of objects that implement each of its classes. This sort is called the natural ordering of the class, and the CompareTo method of the class is called its natural comparison method. It is advisable to make natural sorting consistent with equals.
(2) An object that implements this interface can be used as a key in an ordered map or an element in an ordered collection without specifying a comparer.
(3) int CompareTo (object o): Compares the current object and object o, returns a negative value if it precedes the object o, returns 0 if two objects are in the same position in the sort, or returns a positive value if it is behind the object o
//*****************************************************************************************
//*****************************************************************************************
V. Comparator interface (passed as parameter)
(1) For those classes that do not implement the comparable interface (these classes generally do not have a sort function), to be stored in a tree container, you need to define a comparer to define your own comparison by defining a different class and implementing the comparator interface.
(2) Int Compare (object O1, Object O2): Compares two objects, returns a negative value if O1 is in front of O2, returns a positive value if O1 is behind O2, or 0 if O1 and O2 are considered identical in the sort order.
(3) Similar to comparable, the 0 return value does not mean that the element is equal, only that two objects are in the same position.
//*****************************************************************************************
//*****************************************************************************************
Vi.. Map.entry<k,v> interface
(1) Map's "EntrySet ()" method returns an object "set" that implements the Map.entry interface, and each object in the collection is a "key/value pair" of a specific type "map.entry" in the underlying map.
(2) With this set of iterators, you can get the key or value of each entry and change the value. When an entry is returned through an iterator, unless it is the SetValue () method of the iterator's own remove () method or the entry returned by the iterator, the remainder of the modification to the source map will cause this set of entries to become invalid and the resulting entry behavior undefined.
(3) Object GetKey (): Returns the keyword of the entry
Object getValue (): Returns the value of an entry
Object SetValue (Object value): Changes the value in the associated image to value and returns the old value
//*****************************************************************************************
//*****************************************************************************************
Seven, sortedmap<k,v> interface
(1) Like Setmap, an element added to the SortedMap implementation class (that is, the TreeMap Class) must implement the comparable interface, otherwise you must give its constructor an implementation of the comparator interface.
(2) Comparator Comparator (): Returns the comparer used when sorting "keywords" and returns null if the keyword is compared using the CompareTo () method of the comparable interface)
(2) Object Firstkey (): Returns the first (lowest) keyword in an image
Object Lastkey (): Returns the last (highest) keyword in the image
SortedMap SubMap (Object Fromkey, Object Tokey): Returns the Fromkey view (subset) of elements from Tokey (including) to SortedMap (not included)
//*****************************************************************************************
//*****************************************************************************************
Viii. Collections Class (Tool class for collection class collections, all static methods)
1, "Sort" sort (list) and sort (list,comparator) and Shuffle (list) (random sort)
public static <t extends Comparable<? Super t>> void Sort (list<t> List)
Sorts the specified list in ascending order based on the natural ordering of the elements. All elements in the list must implement the comparable interface. In addition, all elements in the list must be comparable to each other.
public static <T> void sort (list<t> list,comparator<? super t> C) Sorts the specified list according to the order produced by the specified comparer. All elements within this list must be compared to each other using the specified comparer.
2, "reversal" reverse () and Reverseorder () and Reverseorder (Comparator)
public static <T> comparator<t> Reverseorder ()
Returns a comparer that forcibly reverses the natural order of the object collection that implements the comparable interface
public static <T> comparator<t> Reverseorder (comparator<t> cmp)
Returns a comparer that forcibly reverses the order of the specified comparer.
3, "binary search Method" BinarySearch (list,t) and BinarySearch (List,t,comparator)
public static <T> int BinarySearch (list<? extends Comparable<? Super t>> List,t Key)
Searches the specified list for the specified object using the binary search method. Before calling, the list must be sorted in ascending order (via the Sort (list) method) according to the natural ordering of the list elements. If the list is not sorted, the result is indeterminate. If the list contains multiple elements equal to the specified object, it is not guaranteed which one is found.
public static <T> int BinarySearch (list<? extends t> list,t key,comparator<? Super T> C)
The list must be sorted in ascending order according to the specified comparer (via the sort (List, Comparator) method) before the call
4. "Modify" ReplaceAll (List list,object old,object new) replaces all old in the list with new
Fill (List list,object o) replaces all elements in the collection with the specified element o
Swap (list list,int i,int j) Swap list The element at the specified position
Copy (list m,list n) copies all elements in the set N to M, overwriting the elements of the corresponding index
Rotate (list list,int m) The elements in the collection move backward by the M position, and the elements that are obscured later are rotated to the front
5, "Max" Max (Collection) and Max (Collection,comparator)
Min (Collection) and Min (collection,comparator)
Find First indexofsublist (List source,list target) Find the index of the first occurrence location
"Find Tail" lastindexofsublist (List source,list target)
6, "Turn Synchronization" Synchronizedcollection/list/map/set (Collection/list/map/set)
//*****************************************************************************************
//*****************************************************************************************
Ix. Arrays Class (Tool class for Array class [], all static methods)
1, "Sort" sort (arr) sorted by small to large
2, "binary search Method" BinarySearch (Arr,key) pairs of binary search. This sort algorithm is an optimized fast sorting method.
Returns the index if this value exists in the array, otherwise a negative value (-(insertion point)-1) is returned. Note: If there are multiple, you are not sure which one to find.
BinarySearch (Arr,fromindex,toindex,key), including from not including to
The sort (arr) method must be used before the array is sorted, and any result is ambiguous (or possibly negative) if no array is ordered.
3, "Fill" Fill (arr,val) sets all elements of the array to the specified value
Fill (arr,fromindex,toindex,val) sets the element in the specified range of the array to the specified value, including the from does not include to
4, "Judge Equality" Equals (ARR1,ARR2), if two arrays contain the same elements in the same order, then two arrays are equal
Deepequals (ARR1,ARR2), unlike the Equals (object[],object[]) method, this method works for nested arrays of arbitrary depth.
5, "Copy" Copyofrange (arr, int from, int to) copies the specified range of the specified array to a new array, including the from not including to
CopyOf (arr, int newlength) copies the specified array, intercepts or populates with 0 (or false, or null characters) (if necessary) so that the copy has a specified length.
System.arraycopy ((object src, int srcpos, object dest, int destpos, int length) length-number of array elements to copy
Copies the element from the specified source array (SRC) at the specified location (srcpos) to the destination array (dest) and copies the length from the starting position (Destpos).
6, "string" toString (arr) returns the string representation of the array contents. This string form is: "[element], [element], [element]" (separated by commas and spaces)
Deeptostring (object[] a) returns the string representation of the array "deep content". This method is designed to convert a multidimensional array to a string.
such as System.out.println (Arrays.deeptostring (new int[][) {{1, 3, 6}, {2, 7, 9}}); [[1, 3, 6], [2, 7, 9]
7, "hash value" hashcode (arr), returns the hash code based on the contents of the specified array, and if A is null, this method returns 0
Deephashcode (object[] a) returns a hash code based on the "deep content" of the specified array.
8. "Array to set" public static<t> list<t> aslist (T ... a) (A-array of supported lists)
If an element in an array is an object (such as a string), the elements in the array are stored as elements in the collection.
If the element in the array is a base type value, the array is stored directly as an element in the collection.
This method also provides a convenient way to create a fixed-length list that is initialized to contain multiple elements:
List<string> stooges = arrays.aslist ("Larry", "Moe", "Curly");
This method, together with "Collection.toarray ()", serves as a bridge between an array-based API and a collection-based API
Purpose: You can use the collection's methods to manipulate the elements in the array after you have converted to a collection.
Note: The length of the array is fixed, so it is not available for the collection additions or deletions, otherwise the runtime throws an exception

//*****************************************************************************************
//*****************************************************************************************
Keyword features:
See "List": Think of the element "repeatable"
See "Array": it is necessary to think of "arrays", query fast, there is "Corner mark" ★
See "link": it is necessary to think of "linked list", adding and deleting fast, there is the operation of "Frist last" method
See "Set": Think of "uniqueness", elements cannot be duplicated
See "Hash": Want to think "hash table", "Query Fast", to rewrite "hashcode and equals" method ★
See "Tree": it is necessary to think of "binary tree", "to sort", to achieve "comparable or comparator" ★
See "Map": Want to think of "key value pair", key unique

Select by:
Do you need to store a key or a single value?
Key-value pairs: Map (when you are integer, you can consider arrays or ArrayList collections)
Do you need to specify a (healthy) order?
Required: TreeMap
Not required: HashMap
But want a consistent order of storage (ordered): Linkedhashmap
Value: Collection
Do you need elements to be unique?
Required: Set
Do you need to specify the order?
Required: TreeSet
Not required: HashSet
But want a consistent order of storage (ordered): Linkedhashset
Not required: List
Do you need frequent additions or deletions?
Required: LinkedList
Not required: ArrayList


Selection of the list (ArrayList):
For the random query and iteration traversal operations, the array ArrayList is faster than all containers.
From the "middle" position "insert and delete" element, LinkedList is faster than ArrayList, especially the delete operation.
Vectors are often not as fast as ArrayList, and should be avoided, because they are still present in the class library because they support past code.
Best practice: Use ArrayList as the default preference, and select LinkedList only if the program's performance is poor due to the need to frequently insert and delete from the list.
Selection of the Set (HashSet):
The performance of HashSet is always better than treeset (especially the most common add and find element Operations).
The only reason TreeSet exists is that it can maintain the "sort" state of elements, so you should use TreeSet only if you need a well-ordered set.
For insert operations, Linkedhashset is slightly slower than HashSet: This is due to the additional overhead associated with maintaining the list. However, because of the linked list, the "traverse" linkedhashset will be faster than HashSet.
Selection of the map (HASHMAP):
TreeMap are usually slower than hashmap because of the order to maintain.
Linkedhashmap is a bit slower than hashmap because it also maintains a linked list.
The efficiency of Hashtable and HashMap is roughly the same, usually hashmap faster, so HashMap is deliberately replacing Hashtable.
HashMap is designed for "quick query".

Hashcode and equals
The two methods of overriding hashcode and equals are for the collection of hash collections, and for other collections, if you want to find using the contains () method, you only have to implement the Equals () method, and they all use only the Equals method of the object for comparison, not using Hashcode method.

Collection Summary-1

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.