A collections framework is a unified architecture for representing and manipulating collections. It has:

Interfaces: abstract data types representing collections

Implementations: concrete implementations of the collection interfaces

Algorithms: methods that perform useful computations, such as searching and sorting

These algorithms are said to be polymorphic: the same method can be used on different implementations. A collection is a container object that represents a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named sets, lists, and maps.

Java has polymorphic algorithms to provide functionality for different types of collections

public interface Collection<E> extends Iterable<E>

Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn’t provide any direct implementations of this interface but provides implementations of more specific sub interfaces, such as Set and List.

Example:

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

Iterator:

An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.  You get an Iterator for a collection by calling its iterator() method. The following is the Iterator interface.

Example:

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

public interface Set<E> extends Collection<E>

Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as:

  • the cards comprising a poker hand,
  • the courses making up a student’s schedule,
  • or the processes running on a machine.

Example:

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


public interface List<E> extends Collection<E>

List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position).

public interface Map<K,V>

Map — an object that maps keys to values. A Map cannot contain duplicate keys. Each key can map to at most one value. If you’ve used Hashtable, you’re already familiar with the basics of Map.

public interface SortedSet<E> extends Set<E>

SortedSet — a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

public interface SortedMap<K,V> extends Map<K,V>

SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

Example:

public interface SortedMap extends Map{
    SortedMap subMap(K fromKey, K toKey);
    SortedMap headMap(K toKey);
    SortedMap tailMap(K fromKey);
    K firstKey();
    K lastKey();
    Comparator comparator();
}

Using Set

Set set = new HashSet(); // instantiate a concrete set
// ...
set.add(obj); // insert an elements
// ...
int n = set.size(); // get size
// ...
if (set.contains(obj)) {...} // check membership
// iterate through the set
Iterator iter = set.iterator();
while (iter.hasNext()) {
  Object e = iter.next();
  // downcast e
  // ...
}

Example: Set

import java.util.*;
public class Test {
    public static void main(String[] args) {
        Set ss = new LinkedHashSet();
        for (int i = 0; i < args.length; i++)
        	ss.add(args[i]);
        Iterator i = ss.iterator();
        while (i.hasNext())
        	System.out.println(i.next());
    }
}

Using Map

Map map = new HashMap(); // instantiate a concrete map 
// ...
map.put(key, val); // insert a key-value pair 
// ...
// get the value associated with key
Object val = map.get(key);
map.remove(key); // remove a key-value pair
// ... 
if (map.containsValue(val)) { ... }
if (map.containsKey(key)) { ... }
Set keys = map.keySet(); // get the set of keys
// iterate through the set of keys
Iterator iter = keys.iterator();
while (iter.hasNext()) {
  Key key = (Key) iter.next();
  // ...
}

Example:Map

import java.util.*;
public class Test {
	public static void main(String[] args)
	{
		//map to hold student grades
		Map theMap = new HashMap();
		theMap.put("Korth, Evan", 100);
		theMap.put("Plant, Robert", 90);
		theMap.put("Coyne, Wayne", 92);
		theMap.put("Franti, Michael", 98);
		theMap.put("Lennon, John", 88);
		System.out.println(theMap);
		System.out.println("--------------------------------------");
		System.out.println(theMap.get("Korth, Evan"));
		System.out.println(theMap.get("Franti, Michael"));
	}
}

An instance of Map represents a group of objects, each of which is associated with a key. You can get the object from a map using a key, and you have to use a key to put the object into the map. Most of the time you can use the implementations provided for you in the Java API. In case the existing implementations do not satisfy your needs, you can write your own by extending the abstract classes provided in the collections framework.

The Map Interface

The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.

Map Operations

The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null. However, you should not add a Map to itself as a key or value.

  •  Object put(Object key, Object value)
  •  Object remove(Object key)
  •  void putAll(Map mapping)
  •  void clear()

The query operations allow you to check on the contents of the map:

  • Object get(Object key)
  • boolean containsKey(Object key)
  •  boolean containsValue(Object value)
  •  int size()
  •  boolean isEmpty()

The last set of methods allow you to work with the group of keys or values as a collection.

  •  public Set keySet()
  •  public Collection values()
  •  public Set entrySet()

Because the collection of keys in a map must be unique, you get a Set back. Because the collection of values in a map may not be unique, you get a Collection back.

HashMap and TreeMap

The HashMap and TreeMap classes are two concrete implementations of the Map interface. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. Using a HashMap requires that the class of key added have a well-defined hashCode() implementation. With the TreeMap implementation, elements added to the map must be sortable

Example: Using HashMap and TreeMap

This example creates a hash map that maps borrowers to mortgages. The program first creates a hash map with the borrower’s name as its key and mortgage as its value. The program then creates a tree map from the hash map, and displays the mappings in ascending order of the keys.

public class TestMap {
  public static void main(String[] args) {
    // Create a HashMap
    Map<String, Integer> hashMap = new HashMap<String, Integer>();
    hashMap.put("Smith", 30);
    hashMap.put("Anderson", 31);
    hashMap.put("Lewis", 29);
    hashMap.put("Cook", 29);
    System.out.println("Display entries in HashMap");
    System.out.println(hashMap);
    // Create a TreeMap from the previous HashMap
    Map<String, Integer> treeMap =
      new TreeMap<String, Integer>(hashMap);
    System.out.println("\nDisplay entries in ascending order of key");
    System.out.println(treeMap);
  }
}

Output

Display entries in HashMap
{Smith=30, Lewis=29, Anderson=31, Cook=29}
Display entries in ascending order of key
{Anderson=31, Cook=29, Lewis=29, Smith=30}

HashSet and TreeSet

The Collections Framework provides two general-purpose implementations of the Set interface: HashSet and TreeSet. More often than not, you will use a HashSet for storing your duplicate-free collection. For efficiency, objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work properly, elements added to a TreeSet must be sortable

Example:HashSet & TreeSet

import java.util.*;
public class SetExample {
public static void main(String args[]) {
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set.add("Clara");
System.out.println(set);
Set sortedSet = new TreeSet(set);
System.out.println(sortedSet);
}
}

Output

[Gene, Clara, Bernadine, Elizabeth]
[Bernadine, Clara, Elizabeth, Gene

AbstractSet class

The AbstractSet class overrides the equals() and hashCode() methods to ensure two equal sets return the same hash code. Two sets are equal if they are the same size and contain the same elements. By definition, the hash code for a set is the sum of the hash codes for the elements of the set. Thus, no matter what the internal ordering of the sets, two equal sets will report the same hash code.

ListIterator

The ListIterator interface extends the Iterator interface to support bi-directional access, as well as adding or changing elements in the underlying collection. Notice that the ListIterator is originally positioned beyond the end of the list (list.size()), as the index of the first element is 0.

ListIterator iterator = list.listIterator(list.size());
while (iterator.hasPrevious()) {
Object element = iterator.previous();
// Process element
}

Sorting

Classes like String and Integer now implement the Comparable interface to provide a natural sorting order. For those classes without a natural order, or when you desire a different order than the natural order, you can implement the Comparator interface to define your own. To take advantage of the sorting capabilities, the Collections Framework provides two interfaces that use it:

SortedSet and SortedMap

The Comparator Interface

Sometimes you want to insert elements of different types into a tree set. The elements may not be instances of Comparable or are not comparable. You can define a comparator to compare these elements. To do so, create a class that implements the java.util.Comparator interface. The Comparator interface has two methods, compare and equals.

public int compare(Object element1, Object element2)

Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal.

public boolean equals(Object element)

Returns true if the specified object is also a comparator and imposes the same ordering as this comparator.

Example

import java.util.Comparator;
public class GeometricObjectComparator implements Comparator<GeometricObject {
public int compare(GeometricObject o1, GeometricObject o2)
{
 double area1 = o1.getArea();
 double area2 = o2.getArea();
   if (area1 < area2) return -1;
     else if (area1 == area2) return 0;
	 else return 1;
}
}
Tagged with: ClassesJAVAObject Oriented
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.