Collections in Java
Collections in Java
• Arrays
n Has special language support
• Iterators
n Iterator (i)
• Collections (also called containers)
n Collection (i)
n Set (i),
u HashSet (c), TreeSet (c)
n List (i),
u ArrayList (c), LinkedList (c)
n Map (i),
u HashMap (c), TreeMap (c)
OOP: Collections 1
Array
• Most efficient way to hold references to objects.
• Advantages
n An array know the type it holds, i.e., compile-time type checking.
n An array know its size, i.e., ask for the length.
n An array can hold primitive types directly.
• Disadvantages
n An array can only hold one type of objects (including primitives).
n Arrays are fixed size.
OOP: Collections 2
Array, Example
class Car{}; // minimal dummy class
Car[] cars1; // null reference
Car[] cars2 = new Car[10]; // null references
// Aggregated initialization
Car[] cars3 = {new Car(), new Car(), new Car(), new Car()};
cars1 = {new Car(), new Car(), new Car()};
OOP: Collections 4
Collection Interfaces
• Collections are primarily defined through a set of interfaces.
n Supported by a set of classes that implement the interfaces
[Source: java.sun.com]
Collection Iterator
list
isEmpty() hasNext()
add() next()
remove() remove()
...
OOP: Collections 7
The Iterator Interface, cont.
// the interface definition
Interface Iterator {
boolean hasNext();
Object next(); // note "one-way" traffic
void remove();
}
// an example
public static void main (String[] args){
ArrayList cars = new ArrayList();
for (int i = 0; i < 12; i++)
cars.add (new Car());
Iterator it = cats.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());
}
OOP: Collections 8
The Collection Interface
public interface Collection {
// Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object 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();
Object[] toArray(Object a[]);
}
OOP: Collections 9
The Set Interface
• Corresponds to the mathematical definition of a set (no
duplicates are allowed).
OOP: Collections 10
Set Idioms
• set1 ∪ set2
n set1.addAll(set2)
• set1 ∩ set2
n set1.retainAll(set2)
• set1 − set2
n set1.removeAll(set2)
OOP: Collections 11
HashSet and TreeSet Classes
• HashSet and TreeSet implement the interface Set.
• HashSet
n Implemented using a hash table.
n No ordering of elements.
n add, remove, and contains methods constant time complexity
O(c).
• TreeSet
n Implemented using a tree structure.
n Guarantees ordering of elements.
n add, remove, and contains methods logarithmic time complexity
O(log (n)), where n is the number of elements in the set.
OOP: Collections 12
HashSet, Example
// [Source: java.sun.com]
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);
}
}
OOP: Collections 13
The List Interface
• The List interface corresponds to an order group of elements.
Duplicates are allowed.
OOP: Collections 14
The List Interface, cont.
Further requirements compared to the Collection Interface
• add(Object)adds at the end of the list.
• remove(Object)removes at the start of the list.
• list1.equals(list2)the ordering of the elements is
taken into consideration.
• Extra requirements to the method hashCode.
n list1.equals(list2) implies that
list1.hashCode()==list2.hashCode()
OOP: Collections 15
The List Interface, cont.
public interface List extends Collection {
// Positional Access
Object get(int index);
Object set(int index, Object element); // Optional
void add(int index, Object element); // Optional
Object remove(int index); // Optional
abstract boolean addAll(int index, Collection c);
// Optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator();
ListIterator listIterator(int index);
// Range-view
List subList(int from, int to);
}
OOP: Collections 16
ArrayList and LinkedList Classes
• The classes ArrayList and LinkedList implement the
List interface.
OOP: Collections 17
ArrayList, Example
// [Source: java.sun.com]
import java.util.*;
OOP: Collections 18
LinkedList, Example
import java.util.*;
public class MyStack {
private LinkedList list = new LinkedList();
public void push(Object o){
list.addFirst(o);
}
public Object top(){
return list.getFirst();
}
public Object pop(){
return list.removeFirst();
}
OOP: Collections 19
The ListIterator Interface
public interface ListIterator extends Iterator {
boolean hasNext();
Object next();
boolean hasPrevious();
Object previous();
int nextIndex();
int previousIndex();
OOP: Collections 20
The Map Interface
• A Map is an object that maps keys to values. Also called an
associative array or a dictionary.
OOP: Collections 21
The MAP Interface, cont.
public interface Map {
// Basic Operations
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk Operations
void putAll(Map t);
void clear();
// Collection Views
public Set keySet();
public Collection values();
public Set entrySet();
// Interface for entrySet elements
public interface Entry {
Object getKey();
Object getValue();
Object setValue(Object value);
}
}
OOP: Collections 22
HashMap and TreeMap Classes
• The HashMap and HashTree classes implement the Map
interface.
• HashMap
n The implementation is based on a hash table.
n No ordering on (key, value) pairs.
• TreeMap
n The implementation is based on red-black tree structure.
n (key, value) pairs are ordered on the key.
OOP: Collections 23
HashMap, Example
import java.util.*;
System.out.println(m.size()+
" distinct words detected:");
System.out.println(m);
}
}
OOP: Collections 24
Static Methods on Collections
• Collection
n Search and sort: binarySearch(), sort()
n Reorganization: reverse(), shuffle()
n Wrappings: unModifiableCollection,
synchonizedCollection
OOP: Collections 25
Collection Advantages and Disadvantages
Advantages Disadvantages
• Can hold different types of • Must cast to correct type
objects. • Cannot do compile-time type
• Resizable checking.
OOP: Collections 26
Summary
• Array
n Holds objects of known type.
n Fixed size.
• Collections
n Generalization of the array concept.
n Set of interfaces defined in Java for storing object.
n Multiple types of objects.
n Resizable.
OOP: Collections 27