Collections in Java

• Arrays

Has special language support Iterator (i) Collection (i) Set (i),

• Iterators

• Collections (also called containers)
n n

HashSet (c), TreeSet (c) ArrayList (c), LinkedList (c) HashMap (c), TreeMap (c)


List (i),


Map (i),

OOP: Collections


• Most efficient way to hold references to objects.
data index

Car Car
0 1 2

3 4 5

6 7

• Advantages
n n n

An array know the type it holds, i.e., compile-time type checking. An array know its size, i.e., ask for the length. An array can hold primitive types directly. An array can only hold one type of objects (including primitives). Arrays are fixed size.

• Disadvantages
n n

OOP: Collections

// minimal dummy class // null reference // null references for (int i = 0. new Car()}. i < cars2. Car[] cars2 = new Car[10]. cars1 = {new Car(). new Car(). Example class Car{}. new Car().util.Arrays n n n n Search and sort: binarySearch(). sort() Comparison: equals() (many overloaded) Instantiation: fill() (many overloaded) Conversion: asList() 3 OOP: Collections . Car[] cars1.Array. new Car()}. // Aggregated initialization Car[] cars3 = {new Car(). • Helper class java. i++) cars2[i] = new Car().length. new Car().

Corresponds to a bag. 4 OOP: Collections . Can be made not-modifiable. linked list. balanced binary tree • • • • • • Like C++'s Standard Template Library (STL) Can grow as necessary. Can be made thread safe (concurrent access). Heterogeneous. n array. hash table.Overview of Collection • A collection is a group of data manipulate as a single object. • Insulate client programs from the implementation. Contain only Objects (reference types).

Collection Interfaces • Collections are primarily defined through a set of interfaces. 5 OOP: Collections .sun. It is easy to change or replace the underlying collection class with another (more efficient) class that implements the same interface. n Supported by a set of classes that implement the interfaces [Source:] • Interfaces are used of flexibility reasons n n Programs that uses an interface is not tightened to a specific implementation of a collection.

Collection Interfaces and Classes OOP: Collections [Source:] 6 .

... list Iterator hasNext() next() remove() • Iterators are fail-fast n Exception thrown if collection is modified externally. not via the iterator (multi-threading). i.e. OOP: Collections 7 .The Iterator Interface • The idea: Select each element in a collection n Hide the underlying collection Collection isEmpty() add() remove() .

// note "one-way" traffic void remove(). i++) cars. i < 12.out.println ((Car)it. Iterator it = cats. while (it. } OOP: Collections 8 . // the interface definition Interface Iterator { boolean hasNext().add (new Car()). cont. } // an example public static void main (String[] args){ ArrayList cars = new ArrayList().The Iterator Interface.iterator().hasNext()) for (int i = 0. Object next().

// boolean retainAll(Collection c). // // Array Operations Object[] toArray(). boolean addAll(Collection c). boolean add(Object element). // Bulk Operations boolean containsAll(Collection c). // void clear().The Collection Interface public interface Collection { // Basic Operations int size(). } OOP: Collections 9 Optional Optional Optional Optional . // Optional boolean remove(Object element). // Optional Iterator iterator(). boolean contains(Object element). boolean isEmpty(). Object[] toArray(Object a[]). // boolean removeAll(Collection c).

Every constructor must create a collection without duplicates. and set2 ⊆ set1 OOP: Collections 10 .equals(set2) works at follows u set1 ⊆ set2. • Compared to the Collection interface n n n n Interface is identical. The method call set1.The Set Interface • Corresponds to the mathematical definition of a set (no duplicates are allowed). The operation add cannot add an element already in the set.

retainAll(set2) set1.removeAll(set2) • set1 ∩ set2 n • set1 − set2 n OOP: Collections 11 .Set Idioms • set1 ∪ set2 n set1.addAll(set2) set1.

Guarantees ordering of elements. add. remove. No ordering of elements. remove. and contains methods constant time complexity O(c). and contains methods logarithmic time complexity O(log (n)). • HashSet n n n Implemented using a hash table. 12 OOP: Collections .HashSet and TreeSet Classes • HashSet and TreeSet implement the interface Set. add. where n is the number of elements in the set. • TreeSet n n n Implemented using a tree structure.

add(args[i])) System. i < args. for (int i = 0.size() + " distinct words detected: " + s). } } OOP: Collections 13] import java. Example // [Source: java.sun.println("Duplicate detected: " + args[i]).length. i++){ if (!s. } System.*.out. public class FindDups { public static void main(String args[]){ Set s = new HashSet().util.println(s.

lastIndexOf(Object) n Search for elements u n n Specialized Iterator. remove(int).The List Interface • The List interface corresponds to an order group of elements. get(int). set(int. Duplicates are allowed. like arrays u add (int. call ListIterator Extraction of sublist u subList(int fromIndex. int toIndex) OOP: Collections 14 . Object) (note set = replace bad name for the method) indexOf(Object). Object). • Extensions compared to the Collection interface n Access to elements via indexes.

• remove(Object)removes at the start of the list.The List Interface. n list1.hashCode() OOP: Collections 15 . Extra requirements to the method hashCode. cont.hashCode()==list2. Further requirements compared to the Collection Interface • add(Object)adds at the end of the list. • list1.equals(list2) implies that list1.equals(list2)the ordering of the elements is • taken into consideration.

cont. public interface List extends Collection { // Positional Access Object get(int index). // Range-view List subList(int from. Object element). // Optional abstract boolean addAll(int index. } OOP: Collections 16 . // Optional void add(int index. // Optional Object remove(int index). ListIterator listIterator(int index). int to). // Optional // Search int indexOf(Object o). // Iteration ListIterator listIterator().The List Interface. Object element). Object set(int index. Collection c). int lastIndexOf(Object o).

Gives poorer performance on get and set methods compared to ArrayList. n Default choice for simple sequence. • ArrayList is an array based implementation where elements can be accessed directly via the get and set methods. OOP: Collections 17 . • LinkedList is based on a double linked list n n Gives better performance on add and remove compared to ArrayList.ArrayList and LinkedList Classes • The classes ArrayList and LinkedList implement the List interface.

public class Shuffle { public static void main(String args[]) { List l = new ArrayList().*. Collections.shuffle(l.println(l).util.out. new Random()). for (int i = 0. } } OOP: Collections 18 . i++) l. Example // [Source: java. System.length.ArrayList.add(args[i]). i <] import java.

util.LinkedList. } } OOP: Collections 19 . myCar = (Car)s. } public Object pop(){ return list. } public static void main(String args[]) { Car myCar.pop().*. public class MyStack { private LinkedList list = new LinkedList(). public void push(Object o){ list.push (new Car()). Example import java.removeFirst().getFirst(). s.addFirst(o). MyStack s = new MyStack(). } public Object top(){ return list.

} // Optional // Optional // Optional OOP: Collections 20 . void remove(). Object next(). int nextIndex(). void set(Object o). int previousIndex(). void add(Object o). Object previous().The ListIterator Interface public interface ListIterator extends Iterator { boolean hasNext(). boolean hasPrevious().

value) pairs n n n keySet() // returns a Set values() // returns a Collection.The Map Interface • A Map is an object that maps keys to values. and (key. • Methods for adding and deleting n n put(Object key. the values. Object value) remove (Object key) get (Object key) • Methods for extraction objects n • Methods to retrieve the keys. Also called an associative array or a dictionary. entrySet() // returns a set 21 OOP: Collections .

Object value). // Interface for entrySet elements public interface Entry { Object getKey(). int size(). Object remove(Object key). boolean isEmpty(). public Set entrySet(). } } OOP: Collections 22 . // Bulk Operations void putAll(Map t). boolean containsValue(Object value). boolean containsKey(Object key). Object setValue(Object value). public interface Map { // Basic Operations Object put(Object key. // Collection Views public Set keySet(). Object getValue().The MAP Interface. public Collection values(). void clear(). cont. Object get(Object key).

value) pairs. • TreeMap n n The implementation is based on red-black tree structure. OOP: Collections 23 . • HashMap n n The implementation is based on a hash table. value) pairs are ordered on the key.HashMap and TreeMap Classes • The HashMap and HashTree classes implement the Map interface. (key. No ordering on (key.

put(args[i]. } } OOP: Collections 24 . i < args. (freq==null ? ONE : new Integer(freq. m. } System.println(m).println(m. Example import java. public class Freq { private static final Integer ONE = new Integer(1).intValue() + 1))).out.util. System. public static void main(String args[]) { Map m = new HashMap().*. i++) { Integer freq = (Integer) m.size()+ " distinct words detected:").length. // Initialize frequency table from command line for (int i=0.get(args[i]).HashMap.out.

sort() Reorganization: reverse(). shuffle() Wrappings: unModifiableCollection.Static Methods on Collections • Collection n n n Search and sort: binarySearch(). synchonizedCollection OOP: Collections 25 .

Collection Advantages and Disadvantages Advantages Disadvantages • Can hold different types of • objects. Resizable • Must cast to correct type • Cannot do compile-time type checking. OOP: Collections 26 .

Fixed size. Stack. Set of interfaces defined in Java for storing object. • Collections n n n n Generalization of the array concept. Resizable. Deque classes absent n Use LinkedList. 27 OOP: Collections .Summary • Array n n Holds objects of known type. • Queue. Multiple types of objects.

Sign up to vote on this title
UsefulNot useful