Collections Unit4
Collections Unit4
1
Java 2 Collections
• A collection is an object that groups multiple
elements into a single unit
• Very useful
» store, retrieve and manipulate data
» transmit data from one method to another
• Java Collections can achieve all the operations that you
perform on a data such as searching, sorting, insertion,
manipulation, and deletion.
2
Collections Framework
• Unified architecture for representing and
manipulating collections.
• A collections framework contains three things
» Interfaces
» Implementations
» Algorithms
3-February-2003 3
Collections Framework Diagram
3-February-2003 4
Collection Interface
• Defines fundamental methods
» int size();
» boolean isEmpty();
» boolean contains(Object element);
» boolean add(Object element); // Optional
» boolean remove(Object element); // Optional
» Iterator iterator();
3-February-2003 5
Iterator Interface
• Defines three fundamental methods
» Object next()
» boolean hasNext()
» void remove()
• These three methods provide access to the
contents of the collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the
collection
» Then you can use it or remove it
3-February-2003 6
Iterator Position
3-February-2003 7
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}
3-February-2003 8
Collection Framework, Collection & Collections
3-February-2003 10
List Interface
3-February-2003 11
List Interface Context
Collection
List
3-February-2003 12
List Interface
• The List interface adds the notion of order to a
collection
• The user of a list has control over where an element is
added in the collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the elements in
the list.
3-February-2003 13
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
» void add(Object o) - before current position
» boolean hasPrevious()
» Object previous()
3-February-2003 14
Iterator Position - next(), previous()
3-February-2003 15
ArrayList and LinkedList Context
Collection
List
ArrayList LinkedList
3-February-2003 16
List Implementations
• ArrayList
» low cost random access
» high cost insert and delete
» array that resizes if need be
• LinkedList
» sequential access
» low cost insert and delete
» high cost random access
3-February-2003 17
ArrayList overview
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity
3-February-2003 18
ArrayList methods
• The indexed get and set methods of the List interface are
appropriate to use since ArrayLists are backed by an array
» Object get(int index)
» Object set(int index, Object element)
• Indexed add and remove are provided, but can be costly if
used frequently
» void add(int index, Object element)
» Object remove(int index)
• May want to resize in one shot if adding many elements
» void ensureCapacity(int minCapacity)
3-February-2003 19
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and previous
nodes
• Insertion and removal are inexpensive
» just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
» Start from beginning or end and traverse each node while
counting
• Java LinkedList class uses a doubly linked list to store the
elements.
3-February-2003 20
LinkedList entries
private static class Entry {
Object element;
Entry next;
Entry previous;
public LinkedList() {
header.next = header.previous = header;
}
3-February-2003 21
LinkedList methods
• The list is sequential, so access it that way
» ListIterator listIterator()
• ListIterator knows about position
» use add() from ListIterator to add at a position
» use remove() from ListIterator to remove at a position
• LinkedList knows a few things too
» void addFirst(Object o), void addLast(Object o)
» Object getFirst(), Object getLast()
» Object removeFirst(), Object removeLast()
3-February-2003 22
Difference Between ArrayList and LinkedList
ArrayList LinkedList
1) ArrayList internally uses LinkedList internally uses a doubly
a dynamic array to store the linked list to store the elements.
elements.
2) Manipulation with ArrayList Manipulation with LinkedList
is slow because it internally uses an is faster than ArrayList because it
array. If any element is removed from uses a doubly linked list, so no bit
the array, all the other elements are shifting is required in memory.
shifted in memory.
3) An ArrayList class can act as a LinkedList class can act as a list and
list only because it implements List queue both because it implements List
only. and Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.
3-February-2003 23
Difference Between ArrayList and LinkedList
ArrayList LinkedList
5) The memory location for the The location for the elements of a
elements of an ArrayList is linked list is not contagious.
contiguous.
3-February-2003 24
Vector
• The Vector class is designed to function as a dynamic array
that can expand or shrink according to the application’s needs.
• We can access the objects of the Vector using the indices.
• It maintains the insertion order and stores duplicate elements.
• It is found in the java.util package and implements the List
interface
• There are four different types of Vector constructors.
➢ Vector<T> vector = new Vector<T>();
➢ Vector<T> vector = new Vector<T>(int size);
➢ Vector<T> vector = new Vector<T>(int size, int capacityIncrement);
➢ Vector<T> vector = new Vector(Collection<T> collection);
3-February-2003 25
ArrayList Vs Vector
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of current Vector increments 100% means doubles
array size if the number of elements the array size if the total number of
exceeds from its capacity. elements exceeds than its capacity.
5) ArrayList uses the Iterator interface A Vector can use the Iterator interface
to traverse the elements. or Enumeration interface to traverse the
elements.
3-February-2003 26
Stack
• The stack is a linear data structure that is used to store the
collection of objects.
• It is based on Last-In-First-Out (LIFO).
• Java collection framework provides many interfaces and
classes to store the collection of objects.
• Stack is a class that falls under the Collection framework that
extends the Vector class.
• Stack class that provides different operations such as push,
pop, search, etc.
3-February-2003 27
Set Interface
3-February-2003 28
Set Interface
3-February-2003 29
Set Interface Context
Collection
Set
3-February-2003 30
Set Interface
• Same methods as Collection
» different contract - no duplicate entries
• Defines two fundamental methods
» boolean add(Object o) - reject duplicates
» Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
» No guaranteed order in the basic Set interface
» There is a SortedSet interface that extends Set
3-February-2003 31
Set Hierarchy
3-February-2003 32
HashSet and TreeSet Context
Collection
Set
HashSet TreeSet
3-February-2003 33
HashSet
• Java HashSet class is used to create a collection that uses a hash table
for storage.
• It inherits the AbstractSet class and implements Set interface.
• Find and add elements very quickly
» uses hashing implementation in HashMap
• Hashing uses an array of linked lists
» The hashCode() is used to index into the array
» Then equals() is used to determine if element is in the (short) list
of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method must be compatible
» if two objects are equal, they must have the same hashCode()
value
3-February-2003 34
LinkedHashSet
• Java LinkedHashSet class is a Hashtable and Linked list
implementation of the Set interface. It inherits the HashSet
class and implements the Set interface.
The important points about the Java LinkedHashSet class are:
• Java LinkedHashSet class contains unique elements only like
HashSet.
• Java LinkedHashSet class provides all optional set operations
and permits null elements.
• Java LinkedHashSet class is non-synchronized.
• Java LinkedHashSet class maintains insertion order.
3-February-2023 35
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
» Red-Black Trees out of Cormen-Leiserson-Rivest
• An iterator always presents them in order
• Java TreeMap is non synchronized.
• Default order is defined by natural order
» objects implement the Comparable interface
» TreeSet uses compareTo(Object o) to sort
• Can use a different Comparator
» provide Comparator to the TreeSet constructor
3-February-2003 36
Map Interface Context
Map
3-February-2003 37
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
» a single key only appears once in the Map
» a key can map to only one value
• Values do not have to be unique
3-February-2003 38
Map methods
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()
3-February-2003 39
Map views
• A means of iterating over the keys and values in a Map
• Set keySet()
» returns the Set of keys contained in the Map
• Collection values()
» returns the Collection of values contained in the Map.
This Collection is not a Set, as multiple keys can map
to the same value.
• Set entrySet()
» returns the Set of key-value pairs contained in the Map.
The Map interface provides a small nested interface
called Map.Entry that is the type of the elements in this
Set.
3-February-2003 40
HashMap and TreeMap Context
Map
HashMap TreeMap
3-February-2003 41
HashMap Vs. HashSet
HashMap HashSet
Java HashMap is a hash table HashSet is a Set. It creates a
based implementation of Map collection that uses a hash table
interface. for storage.
HashMap implements Map, HashSet implements Set,
Cloneable, and Cloneable, Serializable,
Serializable interface es. Iterable and Collection interfaces
.
In HashMap we store a key-value In HashSet, we store objects.
pair. It maintains the mapping of
key and value.
It does not allow duplicate keys, It does not allow duplicate
but duplicate values are allowed. values.
It can contain a single null It can contain a single null value.
key and multiple null values.
3-February-2003 42
HashMap Vs. HashSet
HashMap uses the put() method HashSet uses the add() method to
to add the elements in the add elements in the HashSet.
HashMap.
HashMap is faster/ than HashSet HashSet is slower than HashMap
because values are associated because the member object is used
with a unique key. for calculating hashcode value,
which can be same for two
objects.
There are two objects created Only one object is created during
during put operation, one the add operation.
for key and one for value.
HashMap internally HashSet internally uses
uses hashing to store objects. a HashMap object to store
objects.
Always prefer when we do not It is used when we need to
maintain the uniqueness. maintain the uniqueness of data.
3-February-2003 43
HashMap and TreeMap
• HashMap
» The keys are a set - unique, unordered
» Fast
• TreeMap
» The keys are a set - unique, ordered
» Same options for ordering as a TreeSet
• Natural order (Comparable, compareTo(Object))
• Special order (Comparator, compare(Object, Object))
3-February-2003 44
HashMap/TreeMap
HashMap TreeMap
HashMap contains value TreeMap also contains value
based on the key. based on the key.
It may have a single null key It cannot have a null key but
and multiple null values. have multiple null values.
HashMap does not maintain TreeMap is sorted by keys.
order while iterating.
It contains unique elements. It contains unique elements.
3-February-2003 45
Comparator interface
• Java Comparator interface is used to order the
objects of a user-defined class.
• This interface is found in java.util package and
contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
• It provides multiple sorting sequences, i.e.,
you can sort the elements on the basis of any
data member, for example, rollno.
3-February-2003 46
Comparable interface
• Java Comparable interface is used to order the
objects of the user-defined class.
• This interface is found in java.lang package
and contains only one method named
compareTo(Object).
• It provides a single sorting sequence only, i.e.,
you can sort the elements on the basis of single
data member only.
3-February-2003 47
compareTo method
• It is used to compare the current object with
the specified object.
• It returns positive integer, if the current object
is greater than the specified object.
• negative integer, if the current object is less
than the specified object.
• zero, if the current object is equal to the
specified object.
3-February-2003 48
Utilities Context
3-February-2003 49
Utilities
• The Collections class provides a number of static
methods for fundamental algorithms
• Most operate on Lists, some on all Collections
» Sort, Search, Shuffle
» Reverse, fill, copy
» Min, max
• Wrappers
» synchronized Collections, Lists, Sets, etc
» unmodifiable Collections, Lists, Sets, etc
3-February-2003 50
Legacy classes
• Still available
• Don’t use for new development
» unless you have to, eg, J2ME, J2EE in some cases
• Retrofitted into Collections framework
• Hashtable
» use HashMap
• Enumeration
» use Collections and Iterators
» if needed, can get an Enumeration with
Collections.enumeration(Collection c)
3-February-2003 51
More Legacy classes
• Vector
» use ArrayList
• Stack
» use LinkedList
• BitSet
» use ArrayList of boolean, unless you can’t stand the
thought of the wasted space
• Properties
» legacies are sometimes hard to walk away from …
3-February-2003 52
Properties class
• The Properties class in Java is used to manage a collection of
key-value pairs, similar to a hashtable.
• It is specifically designed to work with strings for both keys
and values. This makes it particularly useful for storing
configuration settings or other data that can be easily
represented as text.
• Located in java.util package
• Special case of Hashtable
» Keys and values are Strings
» Tables can be saved to/loaded from file
3-February-2003 53
Properties Methods
setProperty() load()
Property’s
store()
getProperty()
propertyNamed()
3-February-2023 54
System properties
• Java VM maintains set of properties that
define system environment
» Set when VM is initialized
» Includes information about current user, VM
version, Java environment, and OS configuration
Properties prop = System.getProperties();
Enumeration e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " value is " +
prop.getProperty(key));
}
3-February-2003 55