The collection framework for Java

Source: Internet
Author: User
Tags addall comparable set set shallow copy shuffle

The Java Collection Framework provides the following two types of containers: 1, Collection (Collection): Access a collection of individual elements. 2. Figure/Map (map): Store key/value pairs (key-value).

Collection interface and Abstractcollection class

Collection interface is the root interface of processing object collection;

Collection (Collection)

The Java Collection Framework supports three main types of collections: 1, ruleset set: To store a set of non-repeating elements 2, linear table list: Used to store an ordered set of elements, where elements can be duplicated. 3 queue: Used to store objects that are processed using FIFO mode.

Note: 1. All the interfaces and classes of the collection framework in Java are defined within the Java.util package. 2. All the concrete classes in the Java Collection Framework implement the java.lang.Cloneable and Java.io.Serializable interfaces. Therefore, their instances are replicable and can be serialized.

Collection interface and Abstractcollection class

Definition: public interface collection<e>extends iterator<e>;
All methods:

Collection in AddAll (); RemoveAll (); Retainall () similar to and in the set, difference, intersection

The collection interface provides basic operations for adding or removing elements from a collection: 1. The Add method adds an element to the collection. 2. The AddAll method adds all the elements in the specified collection to this collection. 3. The Remove method removes an element from the collection. 4. The RemoveAll method deletes all the elements in the specified collection from the collection. 5. The Retainall method retains elements that appear in the current collection and also appear in the specified collection. All of the above methods return a Boolean value, and if the execution method changes the collection, the return is true. The clear () method returns the value type void and simply deletes all the elements in the collection. Note: Method AddAll (), RemoveAll (), Retainall () are similar to the parallel, differential, and intersection operations on the collection.

The collection interface provides a variety of query operations: 1, the Size method returns the number of elements in the collection. 2. The Contains method detects whether the specified element is contained in the collection. 3. The Containsall method detects whether the collection contains elements from the specified collection. 4. The IsEmpty method detects whether the collection is empty. The ToArray method provided by the collection interface returns an array representing the collection. A collection can be either a rule set or a linear table. The iterator interface provides a uniform way to traverse elements in different types of collections.

A collection can be either a rule set or a linear table. The iterator interface provides a uniform way to traverse elements in different types of collections. You can use the iterator () method in the collection interface to return an instance of a iterator interface: 1, its next () method accesses the elements in the collection in order. 2. Its hasnext () method is used to detect if there are more elements in the iterator. 3. Its remove () method removes the last element returned from the iterator.

The Abstractcollection class provides an implementation of some of the abstract methods of the collection interface, which is an abstract class. In addition to the size method and the iterator method, it implements all other methods of the collection interface. The size method and the iterator method give specific implementations in their corresponding subclasses.

Rule Set Set

The set interface extends the collection interface. It does not introduce a new method or constant, but only specifies that the instance of set does not contain duplicate elements. The specific class that implements the set must ensure that no duplicate elements are added to this ruleset. That is, in a ruleset, there must be no element e1, and E2 causes e1.equals (E2) to return to true. The Set interface is defined as follows: public interface set<e> extends Collection<e> Abstractset is a convenience class, It extends the Abstractcollection class and implements the set interface. It provides a concrete implementation of the Equals method and the Hashcode method. The Hashcode (hash code) of a ruleset is the hashcode of all elements in this set. The Abstractset class does not implement the size () method and the iterator () method, so it is an abstract class.

The three concrete classes of the set interface are: Hash class hashset, chain hash set linkedhashset, tree set TreeSet.

Hash set HashSet can use its parameterless construction method to create an empty hash set, or it can create a hash set from an existing collection. By default, the initial capacity is 16 and the guest rate (load factor) is 0.75. If you know the collection size, you can also manually specify the initial capacity and the guest rate. Guest rate (load factor): The value of the guest rate must be between 0.0 and 1.0. It is used to measure the fullness of the set before increasing the capacity of the set. When the number of elements exceeds the product of the capacity and the guest rate, the capacity is automatically doubled. For example, if the capacity is 16 and the guest rate is 0.75. Then, when the size reaches 16x0.75, the capacity will be doubled to 32.

HashSet can store any element that is not the same. Considering the factors of efficiency, the objects added to the set must implement the Hashcode () method in a way that is properly dispersed and hashcode. If two objects of the same type are exactly equal, the hashcode of the two objects must be the same. Since hashset can store elements of different types, this poses a problem: two distinct objects may happen to have the same hashcode. What to do? This situation should be avoided when the hashcode () method is implemented. For example, the Hashcode () method of the integer class returns its int value; the Hashcode () method of the character class returns the uniform code for this character, and so on. HashSet in both integers and character can cause hashcode conflicts.

Chain type hash class Linkedhashset

Linkedhashset uses a linked list to extend the HashSet class, which supports sorting elements within a rule collection. The elements in the Linkedhashset are sorted in the order in which they are inserted. Elements in Linkedhashset cannot be duplicated, and inserting duplicate elements is equivalent to inserting only 1 of times. Note: If you do not need to maintain the order in which elements are inserted, you should use HashSet, which is more efficient than linkedhashset.

Tree-Shaped collection TreeSet

Set expansion order: TreeSet implements the Navigableset interface, the Navigableset interface is the sub-interface of SortedSet, and the SortedSet interface is the sub-interface of the set interface. SortedSet ensures that all elements in the rule collection are ordered. TreeSet is a concrete class that implements the Navigableset interface. In order to create an object of TreeSet, you must ensure that the object types that are added to the treeset are comparable. It can be implemented in two ways: 1, using comparable interface 2, assigning a comparer to the elements in set. The order in which this method is defined is called the comparer order. The comparator comparator will be described later.

Create a TreeSet://When using the statement new TreeSet, create a TreeSet object from a HashSet object and sort the elements in the rule set once//each time to the tree collection TreeSet add elements, and the elements are reordered. treeset<string> TreeSet = new treeset<string> (set);

Methods in TreeSet: System.out.println ("First ():" + Treeset.first ());//Return TreeSet in System.out.println ("Last ():" + Treeset.last ());//Returns the last element in TreeSet System.out.println ("HeadSet (\" New York\ "):" + Treeset.headset ("New York");// Return the part of TreeSet that is smaller than "New York" System.out.println ("HeadSet (\" New York\ "):" + Treeset.tailset ("New York"));//Return to TreeSet The big part of "New York."

Methods in TreeSet: Treeset.first ();//returns the first element in TreeSet treeset.last ();//Returns the last element in TreeSet treeset.headset ("New York");// Return the part of TreeSet that is smaller than "New York" Treeset.tailset ("New York"), or return the part treeset.lower ("Paris") that is larger than "New York" in TreeSet;// Less than the first element of Paris Treeset.higher ("Paris"), or//greater than the first element of Paris Treeset.floor ("Paris");//less than or equal to the first element of Paris treeset.ceiling (" Paris ");//greater than or equal to the first element of Paris Treeset.pollfirst ();//delete and return the first element in the tree collection TreeSet treeset.polllast ();/ Delete and return the last element in a tree collection TreeSet

Note: 1. All concrete classes in the Java Collection framework have at least two constructor methods: one is an parameterless construction method that creates an empty collection, and the other is a construction method that creates an instance of it with a collection object. 2, when it is necessary to make frequent insertions and deletions to the elements in set, it is best to use hashset, because it will reduce the running time of the program. When we need a well-ordered set, we can create a well-ordered set of the HashSet as the treeset of the constructor method.

Comparator interface Comparator

If we need to insert elements into a tree collection but these elements are not instances of the comparable interface at the same time. A comparator can be defined by Java.util.Comparator. The comparator interface has two methods: compare and equals. The public int compare (object Element1, Object Element2) returns a negative value if the element1 is less than Element2, and returns a positive value if the element1 is greater than element2. Equal returns 0. public boolean equals (object element) returns TRUE if the specified object is also a comparer and has the same sort as the current comparer. Note that the Equals method is also defined in the object class. Therefore, even if you do not implement the Equals method in your custom comparer class, there is no compilation error. However, sometimes implementing the Equals method can improve the execution efficiency of the program, because it allows the program to quickly determine whether two different comparators have the same order.

Sometimes we want to insert elements into a treeset, but these elements may not and cannot be defined as instances of java.lang.Comparable. At this time, you can customize a comparator comparator to calculate these elements. Creating a class that implements the Java.util.Comparator interface requires implementing the two methods in the comparator interface: 1, public int Compare (object Element1, Object Element2) Returns a negative value if element1 is less than Element2, returns a positive value if element1 is greater than Element2, or 0 2, public boolean equals (object element) if the specified object is also a comparer and has the same sort as the comparator, it returns true. Because the Equals method is also implemented in the object class. Therefore, the Equals method is not implemented in the custom comparator and there is no compilation error. But sometimes implementing the Equals method allows the program to quickly determine if two different comparators have the same sort, thus improving operational efficiency.

public class Geometricobjectcomparator implements Comparator<geometricobject>, java.io.Serializable {@Override public int Compare (Geometricobject O1, Geometricobject O2) {Double area1 = O1.getarea (); Double area2 = O2.getarea (); if (Area1 < AREA2) {return-1;} else if (area1 > Area2) {return 1;} else {return 0;}} }

Linear table List

The set described earlier can only store elements that are not duplicates. To allow duplicate elements to be stored in the collection, a list (linear table) is used. The list can not only store duplicate elements, but also allow the user to specify where the elements are stored. The user can access the elements in a specific position in the list by subscript. The list interface extends from the collection interface to define an ordered set of allowed duplicates. The list interface adds position-oriented operations, and adds an iterator that iterates through the list in both directions.

Methods in List: 1, method Add (index, Element) is used to specify the subscript index to insert an element elements. 2. Method AddAll (Index, collection) is used to insert a collection collection at the specified subscript. 3. The method Remove (index) is used to remove the element at the specified subscript index from the linear table. 4. The method set (index, Element) can set a new element at the specified subscript index. 5. Method IndexOf (Element) is used to get the index of the first occurrence of the specified element in the list. 6, Method LastIndexOf (Element) is used to obtain the specified element in the list in the last occurrence of subscript 7, Method sublist (FromIndex, Toindex) returns a FromIndex to toIndex-1 from the sub list 8, Method Listiterator () or Listiterator (StartIndex) will return an instance of Listiterator. The listiterator expands the iterator interface to increase the bidirectional traversal capability of the linear table.

Methods in List: 1, method Add (index, Element) is used to specify the subscript index to insert an element elements. 2. Method AddAll (Index, collection) is used to insert a collection collection at the specified subscript. 3. The method Remove (index) is used to remove the element at the specified subscript index from the linear table. 4. The method set (index, Element) can set a new element at the specified subscript index. 5. Method IndexOf (Element) is used to get the index of the first occurrence of the specified element in the list. 6, Method LastIndexOf (Element) is used to obtain the specified element in the list in the last occurrence of subscript 7, Method sublist (FromIndex, Toindex) returns a FromIndex to toIndex-1 from the sub list 8, Method Listiterator () or Listiterator (StartIndex) will return an instance of Listiterator. The listiterator expands the iterator interface to increase the bidirectional traversal capability of the linear table.

Methods in Listiterator: 1, method Add (Element) is used to insert the elements specified in the current list if the next () method defined in the iterator interface returns non-null, the element is immediately inserted into the next () Before the element returned by the previous method, and if the return value of the () method is not null. The element is immediately inserted after the element returned by the previous () method. 2. The method set (element) is used to replace the last element returned by the next method or the previous method with the specified element. 3, Next (), previous (), Nextindex (), Previousindex () methods return the next element in iterator, the previous element, the subscript of the next element, and the subscript of the previous element. 4. Method Hasnext () is used to detect if an iterator has an element while it is traversing forward, and the method hasprevious () is used to detect whether an iterator is traversing backwards for elements.

Methods in Listiterator: 1, method Add (Element) is used to insert the elements specified in the current list if the next () method defined in the iterator interface returns non-null, the element is immediately inserted into the next () Before the element returned by the previous method, and if the return value of the () method is not null. The element is immediately inserted after the element returned by the previous () method. 2. The method set (element) is used to replace the last element returned by the next method or the previous method with the specified element. 3, Next (), previous (), Nextindex (), Previousindex () methods return the next element in iterator, the previous element, the subscript of the next element, and the subscript of the previous element. 4. Method Hasnext () is used to detect if an iterator has an element while it is traversing forward, and the method hasprevious () is used to detect whether an iterator is traversing backwards for elements.

ArrayList and LinkedList are the two concrete classes that implement the list interface. ArrayList uses arrays to store elements, which are created dynamically. If the element exceeds the capacity of the array, a larger array is created and the elements in the current array are copied into the new array. Instead, LinkedList stores elements in a linked list. How to choose ArrayList or LinkedList? In general, choosing ArrayList is more efficient if you need to randomly access elements by subscript, but you cannot insert or delete elements at other locations except at the end (or if you do not need to insert or delete elements). If you need to insert an element anywhere in the list, LinkedList will be a better choice.

ArrayList creation Method: 1, call the parameterless construction method ArrayList () creates an empty list with the default initial value capacity. 2. Call ArrayList (collection) to create an array list from the existing collection collection. 3. Call ArrayList (initialcapacity) to create a list that specifies the initial capacity of initialcapacity.

LinkedList Creation Method: 1, call the parameterless construction method LinkedList () creates a default empty list. 2. Call LinkedList (collection) to create an array list from the existing collection collection.

Note: 1, in order to create a linear table from a variable-length parameter table of a generic type, Java provides a static Aslist method. In this way, you can use the following statement to create a String type list and an integer type of list. List<string> List1 = arrays.aslist ("Red", "green", "blue"); List<integer> List1 = arrays.aslist (1, 2, 3);

Collections Interface

The Java Collection Framework provides static methods for sorting linear tables in the collections class. The collections also contains binarysearch,reverse,shuffle,copy and fill methods for linear tables. and the Max,min,disjoint and frequency methods for the collection.

You can use the method sort (list) to sort the elements in a linear table, where the comparison method uses the CompareTo method in the comparable interface. You can also customize a comparator to compare. list<string> list = arrays.aslist ("Tree", "Apple", "Java"); Collections.sort (list, Collections.reverseorder ()); SYSTEM.OUT.PRINTLN (list);//reverse order Collections.sort (list); SYSTEM.OUT.PRINTLN (list);//sequential arrangement

You can use the method BinarySearch (list, Element) to sort elements in a linear table, and before using the BinarySearch method, be aware that the elements in the array must be ordered in order. If the elements in the list are not ordered in order, an error occurs. System.out.println ("Apple's Index:" + collections.binarysearch (list, "Apple")); SYSTEM.OUT.PRINTLN ("Alpha ' s index:" + collections.binarysearch (list, "alpha"));

You can use the method reverse () to reverse the order of elements in List1 list<integer> list1 = arrays.aslist (1, 2, 10, 4, 3, 7); System.out.println (List1); Collections.reverse (List1);//antagonistic List1 System.out.println (list1);

You can use the method shuffle (list) to randomly reorder elements in a linear table list<integer> List1 = arrays.aslist (1, 2, 10, 4, 3, 7); for (int i = 1; I <= 3; i++) {list<integer> templist = new arraylist<integer> (LIST1); Collections.shuffle (templist);//Disrupt Templist System.out.println ("Shuffle Time:" + i + ".) List1: "+ templist);} for (int i = 1; I <= 3; i++) {list<integer> templist = new arraylist<integer> (list1);//Use random numbers (20), hit Chaotic Templist, the result has the same element sequence Collections.shuffle (templist, New Random (20)); System.out.println ("Shuffle Time:" + i + ".) List1: "+ templist);}

You can use method copy (Det, src) to copy all elements from the source linear table to the target linear table with the same subscript. The target linear table must be as long as the source linear table. If the length of the source linear table is greater than the target linear table, then the remaining elements in the source linear table are not affected. List<integer> List2 = arrays.aslist (1, 2, 3, 4); List<integer> list3 = Arrays.aslist (31, 32); Collections.copy (List2, LIST3); System.out.println ("List2:" + list2);//[31, 32, 3, 4] Note: The copy method is shallow copy. The copy is just a reference to the elements in the linear table.

You can use the method ncopies (int n, Object o) to create an immutable linear table that contains n copies of the specified object. list<date> list4 = collections.ncopies (5, New Date ()); System.out.println ("List4:" + list4); If List4.add (new Date ()) is executed, a java.lang.UnsupportedOperationException is generated. Note here that the list produced using the Ncopies () method is immutable and cannot be added, deleted, or updated in the linear table. All elements in the list produced by the Ncopies () method have the same reference.

Max Method and Min method: You can use the Max method and the Min method to find the largest and smallest elements in the collection. The elements in the collection must use the comparable interface or the comparator interface. list<string> List6 = arrays.aslist ("Red", "green", "blue"); System.out.println ("Max in List6" + Collections.max (LIST6)); System.out.println ("min in List6" + collections.min (LIST6));

If there are no identical elements in the two collection, then the method disjoint returns true collection<string> Collection1 = Arrays.aslist ("Red", "blue"); collection<string> Collection2 = arrays.aslist ("Red", "green"); collection<string> Collection3 = arrays.aslist ("Cyan", "tan"); System.out.println ("Collection1 disjoint collection2:" + collections.disjoint (Collection1, Collection2)); System.out.println ("Collection2 disjoint collection3:" + collections.disjoint (Collection2, Collection3));

Use method frequency (collection, Element) to find out the number of occurrences of an element in the collection list<string> list7 = Arrays.aslist ("Blue", "green", "green"); SYSTEM.OUT.PRINTLN ("Green frequency:" + collections.frequency (list7, "green")); Console Output 2

Here we give a method to test the performance of Set and list as follows: private static long Gettesttime (collection<integer> c, int size) {Long startTime = Sy Stem.currenttimemillis (); list<integer> list = new arraylist<integer> (); for (int i = 0; i < size; i++) {list.add (i);} Collections.shuffle (list); for (int e:list) {c.add (e);} Long EndTime = System.currenttimemillis (); return endtime-starttime;

Vector-like vectors and stacks stack

The Java Collection Framework was introduced in JAVA2. Previous versions of JAVA2 also supported some data structures, including vector-like vectors and stack stacks. To adapt to the Java Collection Framework, JAVA2 has redesigned these classes. In addition to the synchronization methods for accessing and modifying vectors, the vector class is the same as the ArrayList. The synchronization method is used to prevent data corruption when two or more threads are accessing a vector at the same time. For many applications that do not need to use synchronization, using ArrayList is more efficient than using vectors. The stack stack class was also introduced before Java 2. The method empty () is the same as the function of Method IsEmpty (). The method Peek () can return the element at the top of the stack without deleting it. Method POPs () returns the element at the top of the stack and deletes it. The method push (element) adds the specified element to the stack. Method Search (Element) detects whether the specified element is inside the stack.

Queues and Priority queues

A queue is an FIFO data structure. The element is appended to the end of the queue and then deleted from the queue header. In the priority queue, the element is given a priority. When an element is accessed, the element with the highest priority is first deleted.

Double-ended queue deque and linked list LinkedList

The LinkedList implements the Deque interface, and the Deque interface expands the queue interface. Deque is the abbreviation of "double-ended queue" and is usually pronounced "deck". The Deque interface extends the queue interface with an additional method of inserting and deleting elements from both ends of the queue. Methods AddFirst (), Removefirst (), AddLast (), Removelast (), GetFirst (), and getlast () are defined in the Deque interface. The Priorityqueue class implements a priority queue. By default, priority queues use the comparable interface in the natural order of the elements. The element with the smallest value is given the highest priority, so it is first removed from the queue. If several elements have the same highest priority, any of these elements can be removed from the list. You can also use the comparator in the construction method Priorityqueue (initialcapacity, comparator) to specify a sequence.

Map

Suppose you need to store the names of 1 million citizens and their ID numbers in the program, and you need to use a social security number to search for the names of the corresponding people. The most efficient data structure for this task, then, is the mapping (map). Map is a container for storing elements according to key-value values. Key is like subscript. In the list, the subscript is an integer, while in the map the key value key can be any type of object (integer,string). The key value in the map must remain unique, that is, there cannot be duplicate key values, and each key corresponds to a value. A key value key and its corresponding value constitute an item. This item is actually stored in the map.

The map interface provides methods for querying, updating, and retrieving the collection's values and key values for the collection. Here are the update methods: 1, clear () Delete all entries. 2, put (key, value) associates a value with a key value key in map. If the map originally contained a mapping to the key value, the method returns the old value associated with the key value. (instead of associating a key with a new value value) 3, Putall (m) adds the specified map m to the current map, but duplicates items are overwritten. 4. Remove () removes the element corresponding to the specified key from the map.

Query method: 1, ContainsKey (key) to detect whether the map contains the specified key Key-value mapping 2, Containsvalue (value) to detect whether the map contains the key-value of the specified value 3, IsEmpty () detects if map is empty 4, size () returns the number of items in the map

The method of converting map to set: 1, KeySet () calls Map.keyset () takes all the keys in the map to form a set 2, values () call Map.values () that contains all key values. Take all of the value in the map to make a set 3, EntrySet () call Map.entryset () that contains all value values, <key in the map, value> all out to form a containing all <key, The set of the Value> value that each object in the set is a key-value pair in the underlying map. This method actually returns a collection of objects that implement the Map.entry<k, V> interface, where Entry is an internal interface of the map interface.

Abstractmap abstract class: A convenient abstract class that implements the map interface. Abstractmap implements all methods except the EntrySet () method in the map interface. SortedMap interface: Expands the map interface and maintains the <k in the map, v> in ascending order of the key value K. It also has additional methods Firstkey () and Lastkey () return the lowest key value and the highest key value, Headmap (Tokey) return the key value K less than Tokey of that part Map,tailmap (Fromkey) Returns the part of the map with a key value greater than or equal to Fromkey.

1, Concrete class HashMap: For locating a value, inserting a <k, v>, and Deleting a <k, v>, HashMap is the most efficient. The item in the HASHMAP is in no order. 2, the concrete class Linkedhashmap:linkedhashmap uses the list implementation to extend the HashMap class, it supports the item sort in the map. Elements can be sorted either in the order in which they are inserted, or in the order in which they were last accessed. 3, the concrete class treemap:treemap is very efficient when traversing the sequence of key values. The key values can be sorted using the comparator interface or by using the comparable interface.

Single-element and immutable collections and graphs

The collections class contains static methods for linear tables and collections, methods for creating single-element set, list, and map, and methods for creating immutable set, list, and map. The collections class also defines 3 constants: Empty_set, Empty_list, and empty_map, representing empty rule sets, linear tables, and graphs, respectively. Method Singleton () is used to create an immutable set method that contains only one item singletonlist () is used to create an immutable list method that contains only one item Singletonmap () is used to create an immutable map containing only one single key-value pair The Collections class also provides 6 static methods for creating a read-only collection: Unmodifiablecollection (Collection), Unmodifiableset (Set), Unmodifiablelist (List ), Unmodifiablemap (MAP), Unmodifiablesortedmap (SortedMap), Unmodifiablesortedset (SortedSet)

The collection framework for Java

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.