Collection interface of a set frame

Source: Internet
Author: User
Tags addall iterable


The root interface in the Collection hierarchy. Collection represents a set of objects, also known as collection elements. Some collection allow duplicate elements, while others do not. Some of the collection are orderly, while others are unordered. The JDK does not provide any direct implementation of this interface: it provides more specific sub-interfaces (such as Set and List) implementations. This interface is often used to pass collection and operate these collection where it is required to be the most universal.

Package (bag) or multi-collection (Multiset) (unordered collection that may contain duplicate elements) should implement this interface directly.

All common Collection implementation classes (typically indirectly implemented Collection through one of its subinterfaces) should provide two "standard" construction methods: one is void (parameterless) constructed to create an empty Collection; One is a construction method with a single argument of type Collection , which creates a new Collection with the same elements as its parameters. In fact, the latter allows the user to copy any collection to produce an equivalent collection of the desired implementation type. Although this Convention cannot be enforced (because an interface cannot contain a constructor method), all common Collection implementations in the Java platform library follow it.

The "destructive" method contained in this interface refers to those methods that can modify the collection that it operates on, and specifies that these methods throw unsupportedoperationexception If this collection does not support the operation. If so, these methods may, but not necessarily, throw unsupportedoperationexception when the call to the collection is invalid. For example, if the collection to be added is empty and cannot be modified, it is possible, but not necessarily, to throw an exception when calling the AddAll (collection) method on the collection.

Some collection implementations have limitations on the elements they may contain. For example, some implementations prohibit null elements, while some implementations have restrictions on the types of elements. Attempting to add an unqualified element throws an unchecked exception, usually NullPointerException or classcastexception. Attempting to query for an unqualified element might throw an exception, or simply return false; Some implementations will exhibit the previous behavior, while some implementations behave the latter. It is more common to attempt to perform an action on an unqualified element and the completion of the operation does not result in the insertion of unqualified elements into the collection, an exception may be thrown, or the operation succeeds, depending on the implementation itself. Such exceptions are marked as "optional" in the specification of this interface.

Each collection determines its own synchronization policy. In the absence of a strong guarantee of implementation, the invocation of a collection method that is being changed by another process may have an indeterminate behavior, which includes a direct call, passing collection to a method that might execute the call, and checking the collection with an existing iterator.

Many of the methods in the Collectionsframework interface are defined according to the Equals method. For example, the canonical declaration of the CONTAINS (Object O) Method: "Returns True if and only if this collection contains at least one element e that satisfies (o==null? E==null:o.equals (e)). "This specification should not be understood as it implies that calling the Collection.contains method with a non-null parameter o causes the O.equals (e) method to be called for any e element. You can arbitrarily perform optimizations on a variety of implementations, as long as you avoid calling equals, for example, by first comparing the hash codes of two elements. (The Object.hashcode () specification guarantees that two objects with unequal hash codes will not be equal). It is more common that implementations of various collections Framework interfaces are free to take advantage of the specified behavior of the underlying Object method, regardless of whether the implementation program considers it appropriate.

The list of methods is as follows:

Boolean add(Ee)

Make sure that this collection contains the specified element (optional action).

Boolean addall(collection<?extends e> c)

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

void Clear()

Removes all the elements in this collection (optional action).

Boolean contains(Objecto)

Returns True if this collection contains the specified element.

Boolean containsall(collection<?>c)

Returns True if this collection contains all the elements in the specified collection.

Boolean equals(Objecto)

Compares this collection with the specified object for equality.

int hashcode()

Returns the hash code value for this collection.

Boolean isEmpty()

Returns True if this collection contains no elements.

Iterator<e> Iterator()

Returns an iterator that iterates over the elements of this collection.

Boolean remove(objecto)

Removes a single instance of the specified element from this collection, if one exists (optional action).

Boolean removeall(collection<?>c)

Removes all the elements in this collection that are also contained in the specified collection (optional action).

Boolean retainall(collection<?>c)

Leave only those elements in this collection that are also contained in the specified collection (optional action).

int size()

Returns the number of elements in this collection.

Object[] toArray()

Returns an array that contains all the elements in this collection.

<T> t[] toArray(t[] a)

Returns an array containing all the elements in this collection; The run-time type of the returned array is the same as the run-time type of the specified array.

The collection interface contains methods for performing basic operations on the collection, such as size (), isEmpty (), etc., and also defines methods for bulk operations such as Containall (), RemoveAll (), etc.

It is important to note that in some sub-interfaces of collection that cannot contain duplicate values (such as set), when an element is added using the Add () method, if the element already exists in the collection and does not error, it returns a value of false, proving that the collection has changed after the operation

There are two common methods of traversing a collection, one using the For-each method and one using an iterator Iterator

Here's a combination of code examples to gain insight into:

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 inherits the Iterable interface , and classes that inherit the Iterable interface can return an iterator using iterate () . The For-each loop is actually iterating through the elements of the collection using the iterator returned by the iterate () method. In addition to collection subclasses, Arrays in Java also implement the Iterable interface , or you can use the For-each method to iterate

ArrayList we use the For-each method to traverse, and hashset we use the iterator to traverse (and of course the reverse is not a problem), it is important to note that the iterator returns the object type , which requires a type conversion, If you use the For-each iteration, the program will error if you do not specify the type of the collection element (set S = new HashSet ()).

When constructing the hashset, we pass the list as a parameter, but since the set interface does not allow duplicate values, in set it will actually contain only the first four elements in the list, and the Fifth Element "A" is a duplicate value and will not be inserted into the set again. The subclass of collection provides two constructor methods, one of which is parameterless, constructs an empty set, one is a parameter, accepts a collection, transforms it into a set that conforms to its own rules.

In the example above, we use list to refer to the collection instead of the specific implementation class using the list interface, i.e.

set<string> set = new hashset<string> (list)

Rather than

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

This is a good programming habit, because it gives the code more flexibility, and if we want to switch to an ordered set now, we just need to change the construction method.

set<string> set = new Treeset<string> ()

If you are using a concrete implementation class reference, when we replace a collection container, we may also need to modify some of the column methods associated with it, which violates the interface-Oriented programmingThe principle

Collection's ToArray () method can convert a collection to an array, the type stored by default is type object, or it can be determined at run time using generics. The length of the array defaults to the total number of elements of the collection


Collection interface of a set frame

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.