Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Thinking in Java
Prev Contents / Index Next

Collection functionality

The following table shows everything you can do with a Collection (not including the methods that automatically come through with Object), and thus, everything you can do with a Set or a List. (List also has additional functionality.) Maps are not inherited from Collection and will be treated separately.

boolean add(Object)

Ensures that the container holds the argument. Returns false if it doesn’t add the argument. (This is an “optional” method, described later in this chapter.)

boolean
addAll(Collection)

Adds all the elements in the argument. Returns true if any elements were added. (“Optional.”)

void clear( )

Removes all the elements in the container. (“Optional.”)

boolean
contains(Object)

true if the container holds the argument.

boolean containsAll(Collection)

true if the container holds all the elements in the argument.

boolean isEmpty( )

true if the container has no elements.

Iterator iterator( )

Returns an Iterator that you can use to move through the elements in the container.

boolean
remove(Object)

If the argument is in the container, one instance of that element is removed. Returns true if a removal occurred. (“Optional.”)

boolean removeAll(Collection)

Removes all the elements that are contained in the argument. Returns true if any removals occurred. (“Optional.”)

boolean retainAll(Collection)

Retains only elements that are contained in the argument (an “intersection” from set theory). Returns true if any changes occurred. (“Optional.”)

int size( )

Returns the number of elements in the container.

Object[] toArray( )

Returns an array containing all the elements in the container.

Object[]
toArray(Object[] a)

Returns an array containing all the elements in the container, whose type is that of the array a rather than plain Object (you must cast the array to the right type).

Notice that there’s no get( ) method for random-access element selection. That’s because Collection also includes Set, which maintains its own internal ordering (and thus makes random-access lookup meaningless). Thus, if you want to examine the elements of a Collection, you must use an iterator.

The following example demonstrates all of these methods. Again, these work with anything that implements Collection, but an ArrayList is used as a kind of “least-common denominator”:

//: c11:Collection1.java
// Things you can do with all Collections.
import com.bruceeckel.simpletest.*;
import java.util.*;
import com.bruceeckel.util.*;

public class Collection1 {
  private static Test monitor = new Test();
  public static void main(String[] args) {
    Collection c = new ArrayList();
    Collections2.fill(c, Collections2.countries, 5);
    c.add("ten");
    c.add("eleven");
    System.out.println(c);
    // Make an array from the List:
    Object[] array = c.toArray();
    // Make a String array from the List:
    String[] str = (String[])c.toArray(new String[1]);
    // Find max and min elements; this means
    // different things depending on the way
    // the Comparable interface is implemented:
    System.out.println("Collections.max(c) = " +
      Collections.max(c));
    System.out.println("Collections.min(c) = " +
      Collections.min(c));
    // Add a Collection to another Collection
    Collection c2 = new ArrayList();
    Collections2.fill(c2, Collections2.countries, 5);
    c.addAll(c2);
    System.out.println(c);
    c.remove(CountryCapitals.pairs[0][0]);
    System.out.println(c);
    c.remove(CountryCapitals.pairs[1][0]);
    System.out.println(c);
    // Remove all components that are
    //  in the argument collection:
    c.removeAll(c2);
    System.out.println(c);
    c.addAll(c2);
    System.out.println(c);
    // Is an element in this Collection?
    String val = CountryCapitals.pairs[3][0];
    System.out.println("c.contains(" + val  + ") = "
      + c.contains(val));
    // Is a Collection in this Collection?
    System.out.println(
      "c.containsAll(c2) = " + c.containsAll(c2));
    Collection c3 = ((List)c).subList(3, 5);
    // Keep all the elements that are in both
    // c2 and c3 (an intersection of sets):
    c2.retainAll(c3);
    System.out.println(c);
    // Throw away all the elements
    // in c2 that also appear in c3:
    c2.removeAll(c3);
    System.out.println("c.isEmpty() = " +  c.isEmpty());
    c = new ArrayList();
    Collections2.fill(c, Collections2.countries, 5);
    System.out.println(c);
    c.clear(); // Remove all elements
    System.out.println("after c.clear():");
    System.out.println(c);
    monitor.expect(new String[] {
      "[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, " +
        "ten, eleven]",
      "Collections.max(c) = ten",
      "Collections.min(c) = ALGERIA",
      "[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, " +
      "ten, eleven, BURUNDI, CAMEROON, CAPE VERDE, " +
      "CENTRAL AFRICAN REPUBLIC, CHAD]",
      "[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, ten, " +
      "eleven, BURUNDI, CAMEROON, CAPE VERDE, " +
      "CENTRAL AFRICAN REPUBLIC, CHAD]",
      "[BENIN, BOTSWANA, BURKINA FASO, ten, eleven, " +
      "BURUNDI, CAMEROON, CAPE VERDE, " +
      "CENTRAL AFRICAN REPUBLIC, CHAD]",
      "[BENIN, BOTSWANA, BURKINA FASO, ten, eleven]",
      "[BENIN, BOTSWANA, BURKINA FASO, ten, eleven, " +
      "BURUNDI, CAMEROON, CAPE VERDE, " +
      "CENTRAL AFRICAN REPUBLIC, CHAD]",
      "c.contains(BOTSWANA) = true",
      "c.containsAll(c2) = true",
      "[BENIN, BOTSWANA, BURKINA FASO, ten, eleven, " +
      "BURUNDI, CAMEROON, CAPE VERDE, " +
      "CENTRAL AFRICAN REPUBLIC, CHAD]",
      "c.isEmpty() = false",
      "[COMOROS, CONGO, DJIBOUTI, EGYPT, " +
      "EQUATORIAL GUINEA]",
      "after c.clear():",
      "[]"
    });
  }
} ///:~


ArrayLists are created containing different sets of data and upcast to Collection objects, so it’s clear that nothing other than the Collection interface is being used. main( ) uses simple exercises to show all of the methods in Collection.

The following sections describe the various implementations of List, Set, and Map and indicate in each case (with an asterisk) which one should be your default choice. You’ll notice that the legacy classes Vector, Stack, and Hashtable are not included, because in all cases there are preferred classes within the Java 2 Containers.
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire