LevSelector.com New York
home > Java Collections

Java Collections  ( import java.util.*)
 
Interfaces:  
  Collection
   /         \
List       Set
                \
            SortedSet
Map
  |
SortedMap
Interface Implemented By
Set HashSet, TreeSet
List Vector, Stack, ArrayList, LinkedList
Map HashTable, TreeMap, HashMap, WeakHashMap

 
Basic work with Vector/ HashMap 
Vector v = new Vector();
v.addElement("Hello");    
v.addElement(new Integer(99));
v.addElement(99);  // Error, Vector can not store primitives
for (int i=0;i<v.size();i++) System.out.println(v.elementAt(i));   // or v.get(i)
SomeType a = (SomeType) v.remove(4);
 

Iterator ii = v.iterator( );
while (ii.hasNext( )) System.out.println((String) theData.next( ));

HashMap myMap = new HashMap( );
if (myMap.put(myKey, theObject) != null) System.out.println("something wrong");
theObject = (Integer)myMap.remove(theKey);

Iterator kk = myMap.keySet( ).iterator( );
while(kk.hasNext( )) System.out.println((SomeKeyType) kk.next( ));

Let's compare how collections are presented in Perl and in Java.

Collections in Perl: home - top of the page -

Perl:
 Let's say you are comming to Java from Perl.  In perl there are only 2 types of collections: array & hash. You can easily add and remove elements, sort, remove duplicates, join, redimension them, make complicated structures with them, and do whatever else you want - and you can learn it all in 10 minutes, for example:
@a = (1,2,"mam",$some_reference);    # define array and put some elements
$len = @a;  # length of the array, you can also use $#a - the last index of the array
$a[4] =  44;      # add element
push @a, 55;        # add element to the end of the array (use pop to remove it)
                           # also use shift, unshift. ro remove/add elements at the beginning of the array
@sorted = sort @a;    # sort array
@reversed = reverse @a; # reverse the array
foreach $e (@a) { print "$e\n";  }  # go through elements of the array
@joined = (@a1, @a2);   # join 2 arrays

@removed = splice (@a, $ofset, $length, @list);  #  splice() removes the specified elements from the specified array, replacing them with the elements in @list if needed. If no length is specified all the items from offset to the end of the array are removed. 

%hh = ( kk1 => 'vv1', kk2=>'vv2');    # define hash and add some elements
$hh{kk3} = 'vv3';    # add element
if ( exists $hh{kk4} ) {}     # check if an element exists
@ak = keys @a;     # get array of keys
@av = values @a;     # get array of values
for $kk (@ak) { do_something_with $hh{$kk}  }     # go through elements of the hash
while ( ($kk,$vv) = each(%hh) ) {  do_something with $kk and $vv }   # go through elements of the hash
%joined = (%h1, %h2);     # join 2 hashes

delete $hh{kk1};  # delete the element from a hash, return it or the undefined value if nothing was deleted.

you may create anonymous array or hash using  [ .. ]  or  { .. } notation - they return the reference, for example:

$ref_to_array = [ 1,2,3 ];

Because you can store references as values in arrays or hashes - you can easily make multidimensional structures - arrays of arrays or hashes and vice versa. You can do them any depth, flexibly growing your "tree-like" structure, changing the sizes, adding or removing elements or whole sub-trees.

%tree = (
    br1 => [ some_array  ]
    br2 => { some_hash}
);

That's all about perl.  Honestly, this covers IN DETAIL and covers ALL you have to know for 99.99% of your needs working with collections.

 
Java Collections - closer look: home - top of the page -

Now let's see what we have in Java.
Java has ~ 10 different interfaces and numerous classes which I will not even try to list below. Those classes have many methods which, of couse, will not fit here either. So all I will do is provide you with a high-level overview:
First, we have a simple array:

Then we have a class Arrays (with capital "A") - which have some useful methods (for example, sorting or converting to other collection types).
(to sort array of objects you may need them to implement a Comparator interface, which gives you mthod compare()).

   import java.util.Arrays;
   int [] nn = {21,15,3,24};   // array of integers
   Arrays.sort(nn);      // sort in place

Array in Java can store numbers, strings, references to any objects. Arrays can be multi-dimensional.
Negative - all elements of the array should be of the same type.
Another negative - array can't grow.

Original Collections (Java 1.0):
Collections give you capability to store objects of different types - but return them as references of generic "Object" type - you have to explicitly cast the values when you take them out.  Collections allow you to change number of elements. Collections don't allow you to store primitive types (numbers or boolean). 
   Vector class - holds array of Object references. 
   Hashtable class - holds "value" objects indexed by unique "key" objects (dictionary).
   Stack class (Vector with  push & pop methods)
   Enumeration interface - to go through the elements of a collection (vector, hashtable or stack).

Here are some examples of usage of a Vector:
import java.util.*;
Vector v = new Vector();
v.addElement("Hello");
v.addElement(new Integer(99));
v.addElement(99);  // - error, Vector can NOT store primitives
v.addElement(new Double(123.456));
v.remove(2); // remove the 3rd element
for (int i=0;i<v.size();i++) System.out.println(v.elementAt(i));
for (Enumeration e = v.elements(); e.hasMoreElements(); ) { System.out.println( e.nextElement() ) }

Collections have many-many methods.  For example, vector has close to 20 different methods.
With hashtable there are similar methods, most frequent are put(), get(),

import java.util.*;
Hashtable hh = new Hashtable();
String page = "vv1";
String key = "kk1";
hh.put(key,page);
String val = (String) hh.get("kk1");

The New Collections (JDK 1.2):

Collection Interface (java.util.Collection) - the root of all the collections API
Here are related items we will be going through: 
   Six main interfaces: Set (SortedSet), List, Map (SortedMap), Iterator
   Classes: Collections, AbstractCollection, etc.
   Concrete classes to use: ArrayList, HashMap, LinkedList, TreeMap, HashSet, TreeSet, ...

  main interfaces:
    Set (SortedSet) interfaces - no duplicates set of Object references with fixed order
    List interface - ordered collection of objects (Vector implements List)
    Map (SortedMap) interfaces - associate "key" ovjects to "value" objects (Hashtable implements Map)
    Iterator interface - replaces Enumeration.  All classes imlementing Collection must have an iterator method that returns Iterator object.
Iterator methods Enumeration methods
hasNext() hasMoreElements()
next() nextElement()
remove() ---- 

Abstract Classes:
AbstractCollection - implements all methods of Collection exept iterator and size.  Extended by AbstractList and AbstractSet
     AbstractList - implements List interface
     AbstractSet - implements Set interface
AbstractMap - implements Map interface
AbstractSequentialList - extends AbstractList class and provides the basis for LinkedList class.

Some Concrete Classes (there are so many - look in the documentaion):
  ArrayList - extends AbstractList, roughly equivalent to the Vector, but doesn't use synchronized methods - so it is faster.
  HashMap - extends AbstractMap - similar to Hashtable
  LinkedList - implementation of classic linked list data structure
  TreeMap - extends AbstractMap, implements SortedMap

Collections class:
java.util.Collections class - not to be confused with java.util.Collection interface.
Collections class has some useful methods to be applied to misc. collections, for example methods for sorting or searching. Also methods to produce code that inforces synchronized access to the data:
   Map safeMap = Collections.synchronizedMap(myMap);

In this short overview I was not shoing in detail how to work with different classes, because each class has so many fields and methods - it will just take too much space.  Let's consider for example class ArrayList:
Fields inherited from class java.util.AbstractList 
modCount 
  Constructor Summary 
ArrayList() 
          Constructs an empty list. 
ArrayList(Collection c) 
          Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. 
ArrayList(int initialCapacity) 
          Constructs an empty list with the specified initial capacity. 
  Method Summary 
 void add(int index, Object element) 
          Inserts the specified element at the specified position in this list. 
 boolean add(Object o) 
          Appends the specified element to the end of this list. 
 boolean addAll(Collection c) 
          Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. 
 boolean addAll(int index, Collection c) 
          Inserts all of the elements in the specified Collection into this list, starting at the specified position. 
 void clear() 
          Removes all of the elements from this list. 
 Object clone() 
          Returns a shallow copy of this ArrayList instance. 
 boolean contains(Object elem) 
          Returns true if this list contains the specified element. 
 void ensureCapacity(int minCapacity) 
          Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. 
 Object get(int index) 
          Returns the element at the specified position in this list. 
 int indexOf(Object elem) 
          Searches for the first occurence of the given argument, testing for equality using the equals method. 
 boolean isEmpty() 
          Tests if this list has no elements. 
 int lastIndexOf(Object elem) 
          Returns the index of the last occurrence of the specified object in this list. 
 Object remove(int index) 
          Removes the element at the specified position in this list. 
protected  void removeRange(int fromIndex, int toIndex) 
          Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. 
 Object set(int index, Object element) 
          Replaces the element at the specified position in this list with the specified element. 
 int size() 
          Returns the number of elements in this list. 
 Object[] toArray() 
          Returns an array containing all of the elements in this list in the correct order. 
 Object[] toArray(Object[] a) 
          Returns an array containing all of the elements in this list in the correct order. 
 void trimToSize() 
          Trims the capacity of this ArrayList instance to be the list's current size. 
  Methods inherited from class java.util.AbstractList 
equals, hashCode, iterator, listIterator, listIterator, subList 
  Methods inherited from class java.util.AbstractCollection 
containsAll, remove, removeAll, retainAll, toString 
  Methods inherited from class java.lang.Object 
finalize, getClass, notify, notifyAll, wait, wait, wait 
  Methods inherited from interface java.util.List 
containsAll, equals, hashCode, iterator, listIterator, listIterator, remove, removeAll, retainAll, subList 

Now imagine that all other collection classes have similar long lists of available methods.

OK, this was not a detailed coverage for Java collections, because there are too many of them.

Let's summarize:

Perl has 2 types of collections (array & hash)
Java has >10 types, plus many interfaces and abstract classes.

Perl collections - much easier to learn and use.

Java collections creates lots of confusion.  Some of Java collections don't allow you to change number of elements. Others don't allow you to store ellements of different types. They have different methods to do the same thing. I made a test asking java professionals questions about collections in java.  My conclusion - they usually have very limited knowledge of collection classes and methods. They routinely use only couple of them and they are totally confused about others.

-----------------------------------