Collection interface

 

          Provides methods .add(...),  .addAll(...),  .clear( ),  .contains(...),  .containsAll(...),  .isEmpty( ),

            .iterator( ),  .remove(...),  .removeAll(...),  .retainAll(...),  .size( ),  .toArray( )  and  .toArray(...)

 

All the List and Set classes discussed on this site -  ArrayList,  LinkedList,  Vector,  Stack,  HashSet  and  TreeSet - can use these methods.

 

■ The Collection interface defines over a dozen basic methods.  Examples are provided below here under Collection, rather than repeating examples in each class implementing Collection.  See Finding collection methods for a handy chart of where all the collection methods are actually located in the Sun Java API.

 

■ This interface is the basis for Lists and Sets but not Maps. So all Lists and Sets have these methods:

 

 

boolean  .add( Obj )    method

 

■ The .add(...) method returns true if the object in the argument is added without problem.  It returns false if a duplicate of the item is encountered and duplicates are not allowed, as in Sets.  i.e. The snippet can not add the second element to the HashSet.  Instead the second .add(...) returns false. Only the first line prints.

 

import java.util.*;

 

Set hs = new HashSet( );

if ( hs.add( "Element" )) {

    System.out.println("Added 1st");    

    }

if ( hs.add( "Element" )) {

    System.out.println("Added 2nd");    

    }

 

■ The .add(...) method can also be used while ignoring its boolean return information.  i.e.

 

import java.util.*;

     

List list = new ArrayList( );

list.add( "Huey" );

list.add( "Duey" );

list.add( "Louie" );

 

 

boolean  .addAll( Coll )     method

 

■ This method adds all the elements of an entire existing collection specified in the argument. Like .add(...) above, it returns true if successful.  i.e. The snippet below adds the contents of a List to a TreeSet, thus obtaining automatic sorting in the process. It prints the resulting TreeSet elements in alphabeticalorder, even though they weren't entered or added that way.

 

ArrayList = [Minnie, Mickey, Donald]

TreeSet = [Donald, Mickey, Minnie]

 

import java.util.*;

 

List al = new ArrayList( );

al.add( "Minnie" );

al.add( "Mickey" );

al.add( "Donald" );

System.out.println("ArrayList = " + al );

    

Set ts = new TreeSet( );

ts.addAll( al );

System.out.println("TreeSet = " + ts );

 

void  .clear( )     method

 

■ This method simply erases all the elements in your Collection. An exception is thrown if it cannot do so.  i.e. Note that it prints nothing after the .clear( ) is performed:

 

Vector = [ foo, bar]

Vector now = [ ]

 

import java.util.*;

 

Vector v = new Vector( );

v.add( "foo" );

v.add( "bar" );

System.out.println("Vector = " + v );

v.clear( );

System.out.println("Vector now = " + v );

 

 

boolean  .contains( Obj )     method

 

■ This method tests for the presence of the specified element in the collection.  It returns true if the collection contains it.  i.e. This snippet prints successfully:

 

import java.util.*;

 

Stack st = new Stack( );

st.add( "111" );

st.add( "222" );

if (st.contains( "222" )) System.out.println( "Found It!" );

 

 

boolean  .containsAll( Coll )     method

 

■ This method is like .contains(...) above, but it tests for the presence of all the elements in the collection specified in the argument.  It returns true if the first collection contains them all.  i.e. This snippet prints successfully:

 

import java.util.*;

 

Stack st = new Stack( );

st.add( "AAA" );

st.add( "BBB" );

st.add( "CCC" );

st.add( "DDD" );

st.add( "EEE" );

st.add( "FFF" );

 

LinkedList ll = new LinkedList( );

ll.add( "EEE" );

ll.add( "CCC" );

ll.add( "AAA" );

 

if (st.containsAll( ll )) System.out.println( "Found Them All!" );

 

 

boolean  .isEmpty( )     method

 

■ Returns true if the collection contains no elements.  i.e. The following snippet prints successfully because the collection is empty.

 

import java.util.*;

 

HashSet hs = new HashSet( );

// add nothing

if ( hs.isEmpty( ) ) System.out.print( "Nothing there!" );

 

 

iterator( )    method

          See Iterators for information on getting an Iterator.

 

 

boolean  .remove( Obj )     method

 

■ This method removes the first occurrence of the element specified, returning true if successful.  i.e. In the snippet, the first "Larry" is removed, the second "Larry" element still remains, and the code prints as follows:

Curley, Moe, Larry

 

import java.util.*;

 

Stack st = new Stack( );

st.add( "Larry" );                   // add the first "Larry"

st.add( "Curley" );

st.add( "Moe" );

st.add( "Larry" );                   // add a second "Larry"

st.remove("Larry");               // This removes only the first "Larry"

System.out.println( st );

 

 

boolean  .removeAll( Coll )    method

 

■ This is like the above .remove(...) method, but it removes all occurrences of any elements in the second collection specified as the argument.  It returns true if any are removed.  i.e. In the snippet below, the second collection contains a "Larry" and a "Curley" so all the "Larry" elements from the first collection are removed, along with "Curley."  Just "Moe" remains and  Moe  is printed.

 

import java.util.*;

 

ArrayList al = new ArrayList( );

al.add( "Larry" );

al.add( "Curley" );

al.add( "Moe" );

al.add( "Larry" );

 

LinkedList ll = new LinkedList( );

ll.add( "Larry" );

ll.add( "Curley" );

al.removeAll( ll );

System.out.println( al );

 

 

boolean  .retainAll( Obj )    method

 

■ This is the logical opposite of the .removeAll(...) method above. It retains only the elements present in the second collection, deleting everything else. i.e. If the example above is repeated with .retainAll(...) instead of .removeAll(...), all occurrences of "Larry" and "Curley" are retained, and only "Moe" is deleted.  It prints:

Larry, Curley, Larry

 

import java.util.*;

 

ArrayList al = new ArrayList( );

al.add( "Larry" );

al.add( "Curley" );

al.add( "Moe" );

al.add( "Larry" );

 

LinkedList ll = new LinkedList( );

ll.add( "Larry" );

ll.add( "Curley" );

al.retainAll( ll );                                      // retainAll(...) here instead of .removeAll(...)

System.out.println( al );

 

■ If the second collection contains any elements not found in the first collection, processing just proceeds.  A true is returned if any of the elements from the argument collection are found and retained in the first collection. You don't need to find all of the second collection's elements, in other words, to have the first collection modified and get a true. Even one match will do. If none are found, of course, you get a false.

 

 

int  .size( )     method

 

■ This simply returns the number of elements in the collection.  i.e. The snippet prints as follows:

 

.size( ) shows 0

.size( ) shows 3

 

import java.util.*;

 

HashSet hs= new HashSet( );

System.out.println( ".size( ) shows " +  hs.size( ) );

hs.add( "1st" );

hs.add( "2nd" );

hs.add( "3rd" );

System.out.println( ".size( ) shows " +  hs.size( ) );

 

 

Object[ ]  .toArray( )     method

 

Converting collections to arrays.  This method is found in every Collection class. It converts from a List to an Array. It requires an Array cast.  Is the logical opposite of the Arrays.asList(...) method in the Arrays class, which converts from a List to an Array.

 

■ It returns the collection's elements in a new Array, in iterator order. The new Array is safe to modify without modifying the original collection.  i.e.

 

Object[ ] a = anylist.toArray( );

 

■ Since you can't cast the results up from Object [ ], you should probably always use the other .toArray(...) method below.  It lets you specify the runtime type of the resulting array.

 

 

Object[ ]  .toArray( Obj[  ]  )     method

 

■ This handier version of .toArray(...) returns an array of the size and type specified by the array in the argument. You can specify .size( ) in that argument with a new array  to ensure an adequate length.  Note that, in the argument below, String species the type and yourlist.size( ) specifies the length.  i.e.

 

String[ ] a = ( String[ ] ) anylist.toArray( new String[ anylist.size( )] );

 

■ Here's a snippet creating and printing a three-element Array derived from an ArrayList:

 

import java.util.*;

 

ArrayList al = new ArrayList( );

al.add( "Coulda" );

al.add( "Woulda" );

al.add( "Shoulda" );

String[ ] a = ( String[ ] ) al.toArray( new String[ al.size( )] );

for ( int x = 0; x < a.length; x++ ) System.out.println( a[x] );