1 - Java Collections
1 - Java Collections
What is a collection?
A collection (sometimes called a container)
is simply an object that groups multiple
elements into a single unit.
Collections are used to store, retrieve and
See others at
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html
Exercise
Given an ArrayList A of objects write a
method removeDups that removes all
duplicate elements from the list
Introduction
The Collections Framework
◦ A unified architecture for representing and
manipulating collections, allowing them to be
manipulated independently of the details of
their representation.
Here is a hack
Benefits of Collections
Reduces programming effort
Increases program speed and quality
Allows interoperability among unrelated APIs
Reduces the effort to learn and use new APIs:
Reduces effort to design new APIs
Supports software reuse
The Set interface
Set is a collection with NO order
Similar to the Mathematical Abstraction of Set
public interface Set {
// Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element);
// Optional
boolean remove(Object element);
Iterator iterator();
boolean removeAll(Collection c);
boolean retainAll(Collection c);
void clear();
// Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c);
//Array Operations
Object[] toArray(); Object[] toArray(Object a[]);
}
Example: Collections noDups = new HashSet(c );
Examples of using Set
import java.util.*;
public class FindDups {
public static void main(String args[]) {
Set s = new HashSet();
for (int i=0; i<args.length; i++)
if (!s.add(args[i]))
System.out.println("Duplicate detected: "+args[i]);
System.out.println(s.size()+" distinct words detected: "+s);
}
}