Tutorial 3 of Java Collection framework series: Collection Interface

Source: Internet
Author: User
Tags addall

A set represents a group of objects. The collection interface is used to pass the collection of objects and has the strongest versatility. For example, by default, all set implementations have a constructor with a collection type parameter. This constructor is called a conversion constructor. It uses the elements of a specified set to initialize a new set, regardless of the Set interface and implementation type implemented by the specified set. In other words, this constructor allows us to convert the set type (such as list to set, set to list ).

Suppose you have a collection <string> C, which may be a list, a set, or another collection type. According to the above method, we can initialize an arraylist to contain all the elements in C:

List<String> list = new ArrayList<String>();

The following is the collection interface implementation:

public interface Collection<E> extends Iterable<E> {    // Basic operations    int size();    boolean isEmpty();    boolean contains(Object element);    // optional    boolean add(E element);    // optional    boolean remove(Object element);    Iterator<E> iterator();    // Bulk operations    boolean containsAll(Collection<?> c);    // optional    boolean addAll(Collection<? extends E> c);     // optional    boolean removeAll(Collection<?> c);    // optional    boolean retainAll(Collection<?> c);    // optional    void clear();    // Array operations    Object[] toArray();    <T> T[] toArray(T[] a);}

This interface does what we expect a group of objects to do. This interface uses the size and isempty methods to tell us how many elements are in the collection. The contains method is used to determine whether a given element is in the collection. Add or remove elements using the add or remove methods. The iterator method is provided to iterate the access set.

The add method is generalized enough to allow a set of repeated elements and a set of repeated elements. It ensures that the set will contain the specified element after the add method is called, and returns true if the set changes after the add method is called. Similarly, the remove method is used to remove a specified element from the set, provided that the set contains this element and returns true. If the set changes after the remove method is called.

Traverse a set

There are two methods to traverse the set:

  • For-each
  • Iterator access

Fo-each:

For-each access is as follows:

for (Object o : collection)   System.out.println(o);

Iterator access:

An iterator allows us to traverse the set and selectively remove some elements from the set. We can call the iterator method of the set to obtain the set iterator. The iterator interface is as follows:

public interface Iterator<E> {    boolean hasNext();    E next();    void remove(); //optional}

The hasnext method indicates whether there are any elements in the set. Next returns the next element in the iteration. The remove method removes the elements returned by next. Each call to next can only be called once. Otherwise, an exception is thrown. For example, the following code traverses set a and deletes all its elements:

List<String> a = new ArrayList<String>();a.add("hello");a.add("world");Iterator<String> iter = a.iterator();while(iter.hasNext()) {   System.out.print(iter.next() + "\t");   iter.remove(); }

If ITER. Remove is put before ITER. Next (), a java. Lang. illegalstateexception is thrown.

Note that iterator. Remove is the only security method for modifying a set during collection traversal. If you use other methods to modify the set during the traversal of the Set, unexpected events will occur.

Use the iterator instead of the for-each when you need to do the following:-remove the current element. For-each is not a good method for filtering elements in a set. Iterator should be used to filter elements in the set. The Code is as follows:

static void filter(Collection<?> c) {    for (Iterator<?> it = c.iterator(); it.hasNext(); )        if (!condition(it.next()))            it.remove();}

This simple code shows polymorphism, which means it supports all sets regardless of its implementation. This example also demonstrates how simple it is to use the Java Collection framework to write polymorphism algorithms.

Batch operation of collection Interfaces

Batch Operations perform certain operations on the entire set. We can use other basic operations to perform operations on the entire set, although this may not be efficient enough. The following are batch operations supported by the collection interface:

  • Containsall-returns true if the set contains all elements in the specified set
  • Addall-add all elements in the specified set to the target set
  • Removeall-remove all elements that also exist in the specified set from the target set, that is, remove the intersection element from the target set.
  • Retainall-retains only the elements contained in the target set and the specified set, that is, the intersection element. If the target set is modified after retainall is executed, true is returned. When Will false be returned? When the target set contains exactly the same elements as the specified set.
  • Clear-clear all elements in the target set.

The preceding Methods return true, which is modified after the target set executes these methods.

A simple example is provided to prove the power of batch operations. The following code is used to remove the specified Element E from the set:

c.removeAll(Collections.singleton(e));

For another special example, if you want to remove all null elements in the Set:

c.removeAll(Collections.singleton(null));

Collections. Singleton is used here. This is a static factory method, and the returned result is a set that only contains the specified element.

Array Operations of the collection Interface

The toarray method is used to communicate with collections and the old API (expect an array as the input ). The array operation converts the set to an array. The toarray method without any parameters creates a new array of objects. In a more complex form, you can specify an array parameter or select a runtime type for the returned result.

For example, suppose C is a collection. The following code fills the content of C into a new object array. The length of this array is equal to the number of elements of C:

Object[] a = c.toArray();

Assume that C contains only strings, that is, collection <string> C. The following code returns a string array with the length equal to the number of elements in C:

String[] a = c.toArray(new String[0]);

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.