Summary of the Java Collection framework

Source: Internet
Author: User
Tags addall shuffle

In Java we use collections to store and manipulate a set of data that is not fixed, and that the collection contains references to objects, not to the object itself, which is why the base type data cannot be stored in the collection. Most of the collection classes are in the Java.util package, the Java collection architecture has two interfaces collection and map for subclasses, and the Java Collection schema supports 3 types of collections: Rule set (set), Linear table (list), and diagram (map), respectively, defined in Set,list,map. A set instance stores a set of distinct elements (collections), a list instance stores a set of sequential elements (tables), and a map stores a set of objects---a mapping of key values.

Learn the contents of the Java Collection framework, and personally think you should be familiar with the following:

First, familiar with the common Java Collection framework hierarchy structure

Second, the characteristics of the common set class and the structure of the bottom

ArrayList bottom is an array, the array of elements of the same type, each element occupies the same amount of space, and the entire array of storage space is continuous, so as long as you know the first element address, plus subscript, through the mathematical expression can quickly locate any element in the array, the search efficiency is high, The disadvantage is to ensure continuous, each deletion operation involves the displacement of the subsequent elements, in the actual use of subscript query less opportunities, in order to improve the efficiency of the array query, will use binary lookup (dichotomy), if the elements in the array by size order.

LinkedList Bottom is a doubly linked list, in addition to the first element and the tail element, each element has an index pointing to its previous element and the latter element, so the deletion efficiency is higher, the query must start from the first element of a node down, so the query efficiency is low.

The queue (queue) interface is implemented indirectly by LinkedList, so it can be used to emulate the structure of the queues, as follows:

You can also use LinkedList to simulate the stack data structure, the code is as follows:

HashMap Store Key-value pairs in the form of <K,V>, the bottom is a hash table, the hash table is neither a purely group, nor a pure linked list, but a chain of tables and arrays of the Union, you can think of a hash table is a one-way list of each node is an array, You need to override the Hashcode () and Equals () methods while storing in HashMap. The key part of HashMap is a hashset,hashmap with high efficiency of query and deletion.

Likedhashmap: stored in the order of addition, can be removed in the order of addition, by using it in the foreground to generate a fixed sequence of drop-down list, its key part is likedhashset.

Treehashmap: The elements stored in it can be sorted according to certain rules, so the element that holds it must implement the comparable interface, or a separate comparator to implement the comparator interface, Typically, the latter is recommended for code reuse if it is necessary to put the treehashmap element in more types and compare the same rules. Treehashmap Bottom is a sortable binary tree, it follows the principle of small and large left, its bottom of the traversal of its use of the middle sequence traversal, so the iterative elements of the total movement from the bottom to the large arrangement, its key value part is a treeset.

Third, use common methods defined by the collection interface and the map interface to manipulate the collection

1.Collection interface

Used to represent any object or group of elements. This interface is used when you want to handle a set of elements in the usual way possible.

(1) Single element Add, delete operation:

Boolean Add (Object o): Add an object to the collection

Boolean remove (Object O): If there are objects in the collection that match O, delete the object o

(2) Query operation:

int size (): Returns the number of elements in the current collection

Boolean IsEmpty (): Determines whether there are any elements in the collection

Boolean contains (Object O): Finds whether the collection contains objects O

Iterator Iterator (): Returns an iterator to access the individual elements in the collection

(3) Group actions: Acting on an element group or an entire collection

Boolean containsall (Collection C): Finds whether the collection contains all the elements in collection C

Boolean AddAll (Collection C): Adds all elements of collection C to the collection

void Clear (): Delete all elements in the collection

void RemoveAll (Collection c): Removes all elements of collection C from the collection

void Retainall (Collection c): Removes elements not contained in collection C from the collection

(4) Collection converted to an object array:

Object[] ToArray (): Returns an array containing all the elements of the collection

Object[] ToArray (object[] a): Returns an array containing all the elements of the collection. The array returned by the runtime is the same as the type of parameter A and needs to be converted to the correct type.

In addition, you can convert a collection to any other array of objects. However, you cannot directly convert the collection to an array of base data types, because the collection must hold the object.

2.Iterator interface
The Iterator () method of the Collection interface returns a Iterator. The iterator interface method iterates through each element of the collection in an iterative manner and safely removes the appropriate element from the collection.
(1) Boolean hasnext (): Determines whether there is another accessible element.
(2) void Remove (): Deletes the object returned from the last access. This method must be executed immediately after the access of an element. Iterraor.remove is the only safe way to remove elements during traversal of a collection.

3.List interface

The List interface inherits the Collection interface to define an ordered set of allowed duplicates. This interface is not only able to process a part of the list, but also adds a location-oriented operation.

Location-oriented operations include the ability to insert an element or Collection, and also to get, drop, or change the functionality of an element. Searching for elements in a list can start with the head or tail of the listing, and if the element is found, the location of the element is also reported:

void Add (int index, Object Element): Elements element is added at the specified position index

Boolean addall (int index, Collection c): Adds all elements of collection C to the specified position index

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 element on position index with element elements, and returns the old element

4.ListIterator interface

The Listiterator interface inherits the Iterator interface to support adding or changing elements in the underlying collection, and also supports bidirectional access. Listiterator has no current position, the cursor is between the values returned by the call previous and the next method. A list of length n with a n+1 valid index value:

(1) 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. If the list structure has been modified since the last call, the IllegalStateException exception will be thrown.

(2) Boolean hasprevious (): Determines if there are elements accessible to the backward Iteration object Previous (): Returns the previous object

Intnextindex (): Returns the index of the element that will be returned the next time the next method is called

Intpreviousindex (): Returns the index of the element that will be returned the next time the previous method is called

Normally, you don't have to listiterator change the direction of a collection element-either forward or backward. Although technically achievable, previous () immediately calls next (), returning the same element. Reverse the order of calls to next () and previous (), and the result is the same.

5. Map interface

The map interface is not an inheritance of the collection interface. The map interface is used to maintain key/value pairs (Key/value pairs). This interface describes a key-to-value mapping that is never duplicated.

(1) Add, delete operation:

Object put (object key, Object value): Places a keyword associated with one value into the image. If the keyword already exists, the new value associated with this keyword supersedes the old value. method returns the old value of the keyword, or null if the keyword does not originally exist

Object remove (Object key): Remove key-related mappings from the image

void Putall (Map t): Adds all elements from a specific image to the image

void Clear (): Remove all mappings from the image the key and value can be null. However, you cannot add a map as a key or value to itself. ”

(2) Query operation:

Object get (Object key): Gets the value associated with the keyword key and returns the object associated with the keyword key, or null if no keyword is found in the image

Boolean ContainsKey (Object key): Determine if there is a keyword key in the image

Boolean Containsvalue (Object value): Determines whether the value exists in the image

int size (): Returns the number of mappings in the current image

Boolean IsEmpty (): Determine if there are any mappings in the image

(3) View actions: Working with the key/value pairs group in the image

Set KeySet (): Returns the set of views for all keywords in the image

Because the collection of keys in the map must be unique, you use set support. You can also delete an element from the view, while the keyword and its associated values are removed from the source image, but you cannot add any elements.

Collection values (): A view set that returns all values in the image

Because the collection of values in the map is not unique, you use collection support. You can also delete an element from the view, while the value and its keywords will be removed from the source image, but you cannot add any elements.

Set EntrySet (): Returns the view set of the Map.entry object, which is the keyword/value pair in the image

Because the mappings are unique, you use set support. You can also remove elements from the view, and these elements will be removed from the source image, but you cannot add any elements.

6map.entry interface

The map's EntrySet () method returns a collection of objects that implement the Map.entry interface. Each object in the collection is a specific key/value pair in the underlying map. With this set of iterators, you can get keys or values for each entry (the only way to get it) 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.

(1) Object GetKey (): Returns the keyword of the entry

(2) Object getValue (): Returns the value of an entry

(3) Object SetValue (object value): Changes the value in the associated image to value and returns the old value

Iv. iterator interface Traversal collection and collection traversal using the JDK's enhanced for loop

1.ArrayList

2.HashMap

V. Static methods that will use the collections class

The Collections tool class provides a number of operations for COLLECTION/MAP, which can be divided into four categories:

1. Sort operation (mainly for list interface)

Reverse (List List): Reverses the order of the elements in the specified list collection

Shuffle (List list): Randomly sort the elements in the list (shuffle)

Sort (List List): Sorts the elements in the list according to the natural ascending order

Sort (List list, Comparator C): Sorting by custom comparer

Swap (list list, int i, int j): Swaps the I and J elements in the specified list collection

Rotate (list list, int distance): Shifts all elements to the right by the specified length, if distance equals size then the result is unchanged

2. Find and replace (mainly related to collection interface)

BinarySearch (List list, object key): Uses the binary search method to get the index of the specified object in the list, provided that the collection is sorted

Max (Collection coll): returns the largest element

Max (Collection Coll, Comparator comp): Returns the largest element based on the custom comparer

Min (Collection coll): returns the smallest element

Min (Collection coll, Comparator comp): Returns the smallest element according to the custom comparer

Fill (List List, object obj): Fills with the specified object

Frequency (Collection object O): Returns the number of occurrences of the specified object in the specified collection

ReplaceAll (List List, object old, object new): Replace

3. Synchronization control

The Collections tool class provides multiple synchronizedxxx methods that return synchronization objects corresponding to the specified collection object, thereby addressing the thread's security issues when multithreading concurrently accesses the collection. HashSet, ArrayList, HashMap are thread insecure, and if you need to consider synchronization, use these methods. These methods mainly include: Synchronizedset, Synchronizedsortedset, Synchronizedlist, Synchronizedmap, Synchronizedsortedmap.

In particular, you need to manually synchronize the returned collection when iterating through the collection using an iterative method.

4. Set immutable Sets

Collections There are three ways to return an immutable collection

EMPTYXXX (): Returns an empty Immutable collection object

SINGLETONXXX (): Returns a Immutable collection object that contains only the specified object.

UNMODIFIABLEXXX (): Returns the immutable view of the specified collection object

Vi. Some other additions to the collection classes

1. Use of collections in multi-threaded environments:

We know that HashMap is non-thread safe, and when we have only one thread in use HASHMAP, naturally there is no problem, but if multiple threads are involved and there is a read and write process, HASHMAP will not be able to meet our needs (Fail-fast). In the case of performance problems, our solution has hashtable or collections provide synchronous method, both of which basically is the entire hash table structure to do locking operations, so during the lock table, other threads need to wait, no doubt performance is not high.

At this point we can consider using Concurrenthashmap instead of synchronous map, which essentially uses a more coarse-grained lock, which locks only part of the container during the iteration, thus greatly improving the execution efficiency of the program in the multi-threaded environment.

Copyonwritearraylist:list implementations each update produces a new, implicitly-array copy, so this is a costly operation. Typically used in a collection where the traversal operation is more than the update operation, such as the Listeners/observers collection.

2. How to remove elements from collection with proper side traversal

The only correct way to remove an element from an collection in an edge traversal is to use the Iterator.remove () method

3. How to delete duplicate elements in ArrayList

If you do not care about the order of elements in ArrayList, you can put the list in the set to remove the repeating elements and then put them back, if the order of care can be linkedhashset.

4. Orderly Collection

The sort method of the collection can be sorted on the list,

Priotrityqueue Dynamic maintenance of an orderly queue (re-ordering each deletion and additions)

If there are no duplicate elements in collection, then TreeSet is also a choice

Summary of the Java Collection Framework

Related Article

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.