Collection interface of collection framework, Collection framework

Source: Internet
Author: User

Collection interface of collection framework, Collection framework


The Root Interface in the Collection hierarchy. Collection represents a group of objects, also known as collection elements. Some collections allow repeated elements, while others do not. Some collections are ordered, while others are disordered. JDK does not provide any direct implementation of this interface: it provides more specific sub-interfaces (such as Set and List. This interface is usually used to pass collections and operate these collections where the maximum universality is required.

This interface should be directly implemented in a bag or multi-set (unordered collection that may contain duplicate elements.

All common Collection implementation classes (usually indirectly implementing Collection through a sub-interface) should provide two "standard" constructor methods:One is the void (No parameter) constructor.To create an empty collection.One is the construction method with Collection type single parameterTo create a collection with the same elements as its parameters. In fact, the latter allows the user to copy any collection to generate an equivalent collection of the desired implementation type. Although this convention cannot be enforced (because the interface cannot contain constructor methods), all common Collection implementations in the Java platform library follow it.

The "destructive" method contained in this interface refers to the methods that can be used to modify the collection objects to be operated on. If this collection does not support this operation, specify these methods to throw UnsupportedOperationException. If so, these methods are possible when the call is ineffective for the collection, but do not necessarily throw UnsupportedOperationException. For example, if the collection to be added is empty and cannot be modified, an exception may not be thrown when the addAll (collection) method is called for the Collection.

Some collection implementations have restrictions on the elements they may contain. For example, some implementations prohibit null elements, while some implementations limit the type of elements. Attempting to add an unqualified element will throw an unchecked exception, usually NullPointerException or ClassCastException. An attempt to query whether an element is unqualified may throw an exception or simply return false. Some implementations will show the previous behavior, while some implementations will show the latter. It is common that an attempt to perform an operation on an unqualified element will not insert the unqualified element into the collection, and an exception may be thrown, the operation may also succeed, depending on the implementation itself. This exception is marked as "optional" in this interface specification ".

Each collection determines its own synchronization policy. Without a strong guarantee of implementation, the method that calls the collection being changed by another process may be uncertain; this includes direct calls, pass the collection to methods that may be called and use an existing iterator to check the collection.

Many methods in the CollectionsFramework interface are defined according to the equals method. For example, the canonicalized declaration of the contains (Object o) method: "if and only when this collection contains at least one satisfied (o = null? E = null: If the Element e of o. equals (e) is null, true is returned ." This specification should not be understood as it implies that calling the Collection. contains method with non-null parameter o will cause the o. equals (e) method to be called for any e element. You can optimize various implementations at will, as long as you do not need to call equals, for example, by comparing the hash codes of the two elements first. (The Object. hashCode () specification ensures that two objects whose hash codes are not equal ). It is common that the implementation of various Collections Framework interfaces can randomly use the specified behavior of the underlying Object method, regardless of whether the implementation program deems it appropriate.

The method list is as follows:

BooleanAdd(Ee)

Make sure that the collection contains the specified elements (optional ).

BooleanAddAll(Collection <? Extends E> c)

Add all elements in the specified collection to this collection (optional ).

VoidClear()

Removes all elements from the collection (optional ).

BooleanContains(Objecto)

Returns true if the collection contains the specified element.

BooleanContainsAll(Collection <?> C)

Returns true if the collection contains all elements in the specified collection.

BooleanEquals(Objecto)

Compare whether the collection is equal to the specified object.

IntHashCode()

Returns the hash value of this collection.

BooleanIsEmpty()

Returns true if the collection does not contain any element.

Iterator <E>Iterator()

Returns the iterator that iterates on the elements of this collection.

BooleanRemove(Objecto)

Remove a single instance of the specified element from this collection. If yes (optional ).

BooleanRemoveAll(Collection <?> C)

Removes all elements in the collection that are also included in the specified collection (optional ).

BooleanRetainAll(Collection <?> C)

Only the elements in the collection that are also included in the specified collection are retained (optional ).

IntSize()

Returns the number of elements in the collection.

Object []ToArray()

Returns an array containing all elements in the collection.

<T> T []ToArray(T [])

Returns an array containing all elements in the collection. The runtime type of the returned array is the same as the runtime type of the specified array.

 

The Collection Interface contains methods for performing basic operations on a set, such as size () and isEmpty (). It also defines methods for batch operations, such as containAll () and removeAll ().

Note that when you use the add () method to add an element in a Collection sub-interface (such as Set) that cannot contain duplicate values, if the element already exists in the Collection, no error is reported, but a false value is returned to prove that the set has changed after this operation.

Traverse a setThere are two common methods:For-eachMethod, one is to use the iteratorIterator

The following is an example of code:

List <String> list = new ArrayList<String>();         list.add("a");         list.add("b");         list.add("c");         list.add("d");         list.add("a");                 for(Stringstr : list){                System.out.println(str);         }                 Set<String>set = new HashSet<String>(list);         Iteratorit = set.iterator();         while(it.hasNext()){                Stringstr = (String)it.next();                System.out.println(str);         }

Both List and Set are sub-interfaces of Collection, and the Collection interface inheritsIterable InterfaceClass that inherits the Iterable interface can useIterate ()Returns an iterator. the for-each loop actually uses the iterator returned by the iterate () method to iterate the elements of the set. Except the subclass of Collection,JavaThe array in also implements the Iterable InterfaceYou can also use the for-each method for iteration.

In ArrayList, we use the for-each method for traversal, while in HashSet, we use Iterator for traversal (of course, this is also not a problem). Note that,The iterator returns the Object type.Type conversion is required. If you use for-each iteration, the program reports an error if the Set element type is not specified (Set s = new HashSet.

When constructing a HashSet, we pass the list as a parameter. However, because the Set interface does not allow repeated values, the set interface actually only contains the first four elements in the list, the fifth element "a" is a duplicate value and will not be inserted into the set again. The Collection subclass provides two constructor Methods: one is non-parameter, and the other is an empty set. The other is a parameter, and the other is a Collection, convert it to a set that complies with its own rules

In the above example, we use List to reference the set, instead of using the specific implementation class of the List interface, that is

Set<String> set = new HashSet<String>(list)

Rather

HashSet <String> set = new HashSet<String>(list)

This is a good programming habit, because it gives code more flexibility. If we want to change to an ordered set, we only need to change the constructor method.

Set<String> set = new TreeSet<String>()

If we use a specific implementation class reference, when we replace a collection container, we may also need to modify some column methods related to it, which violates Interface-Oriented ProgrammingPrinciples

The toArray () method of Collection can be used to convert a set into an array. The default type of array storage is the Object type, or the generic type can be determined at runtime. The length of the array is equal to the total number of elements in the set by default.


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.