Chapter 6
Chapter 6
1
Introduction
• In order to handle group of objects we can use array of
objects.
• If we have a class called Employ with members name
and id, if we want to store details of 10 Employees,
create an array of object to hold 10 Employ details.
Employ ob [] = new Employ [10];
We cannot store different class objects into same
array.
Inserting element at the end of array is easy but at
the middle is difficult.
After retrieving the elements from the array, in order
to process the elements we don't have any methods
2
Java Collections Framework
• It is a Pre packaged Implementation
• Unified architecture for representing and manipulating collections.
• All collections frameworks contain the following:
• Interfaces:
• are abstract data types that represent collections.
• allow collections to be manipulated independently of the details
of their representation.
• Implementations, i.e., Classes:
• are the concrete implementations of the collection interfaces.
• are reusable data structures.
• Algorithms:
• are the methods that perform useful computations, such as
searching and sorting, on objects that implement collection
interfaces.
• are said to be polymorphic: that is, the same method can be used
on many different implementations of the appropriate collection
interface. 3
Hierarchy of Collection Framework
6
Collection Interface
Defines fundamental methods
int size();
boolean isEmpty();
Iterator iterator();
7
Iterator Interface
Defines three fundamental methods
Object next()
boolean hasNext()
void remove()
8
Example
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++) { Output:
c.add(i + " * " + i + " = "+i*i); java.util.ArrayList
1*1=1
} 2*2=4
Iterator iter = c.iterator(); 3*3=9
while (iter.hasNext()) 4 * 4 = 16
5 * 5 = 25
System.out.println(iter.next()); 6 * 6 = 36
} 7 * 7 = 49
} 8 * 8 = 64
9 * 9 = 81
10 * 10 = 100
9
List Interface
List
ArrayList LinkedList
Indexed add and remove are provided, but can be costly if used
frequently
void add(int index, Object element)
counting
14
LinkedList Methods
The list is sequential, so access it that way
ListIterator listIterator()
15
Example: LinkedList
Program that shows the use of LinkedList class.
import java.util.*;
class LinkedDemo
{ public static void main(String args[])
{ LinkedList <String> ll = new LinkedList<String>();
ll.add (" Africa");
ll.add ("North America");
ll.add ("South America");
ll.add (“Asia");
ll.addFirst ("Europe");
ll.add (1,"Australia");
ll.add (2,"Antarctica");
System.out.println("Elements in Linked List is : " + ll);
System.out.println("Size of the Linked List is : " + ll.size() );}}
16
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
Set
compatible
18
if two objects are equal, they must have the same hashCode()
TreeSet
Elements can be inserted in any order
19
LinkedHashSet
• LinkedHashSet maintains a linked list of the entries in the set, in the order in
which they were inserted.
• This allows insertion-order iteration over the set.
• The hash code is used as the index at which the data associated with the key is
stored. The transformation of the key into its hash code is performed automatically.
• The LinkedHashSet class supports four constructors.
• The first form constructs a default hash set: LinkedHashSet( )
• The following constructor form initializes the hash set by using the elements of
c.
LinkedHashSet(Collection c)
• The following constructor form initializes the capacity of the hash set to
capacity. The capacity grows automatically as elements are added to the Hash.
LinkedHashSet(int capacity)
• The fourth form initializes both the capacity and the fill ratio (also called load
capacity) of the hash set from its arguments:
LinkedHashSet(int capacity, float fillRatio)
20
Set Implementation Comparisons
21
Example: HashSet and Iterator
Program 1: Program shows the use of HashSet and Iterator.
import java.util.*;
class HS
{ public static void main(String args[])
{ //create a HashSet to store Strings
HashSet <String> hs = new HashSet<String>();
//Store some String elements
hs.add (“Ethiopia");
hs.add ("America");
hs.add ("Japan");
hs.add ("China");
hs.add ("America");
hs.add(“N. Korea”);
//view the HashSet
System.out.println ("HashSet = " + hs);
//add an Iterator to hs
Iterator it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{ String s = (String) it.next ();
System.out.println(s);}}} 22
Map Interface
Stores key/value pairs
Maps from the key to the value
Keys are unique Map
a single key only appears once in the Map
a key can map to only one value
HashMap TreeMap
Values do not have to be unique
HashMap
The keys are a set - unique, unordered
Fast
TreeMap
The keys are a set - unique, ordered
Same options for ordering as a TreeSet
23
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()
24
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. 25
Example: HashMap
Program that shows the use of HashMap class.
import java.util.*;
class HashMapDemo
{ public static void main(String args[])
{
HashMap<Integer, String> hm = new HashMap<Integer, String>
();
hm.put (101,"Alemu");
hm.put (102,"Kuma");
hm.put (103,"Hanna");
hm.put (104,"Mahesh");
hm.put (105,"Chaltu");
Set<Integer> set = new HashSet<Integer>();
set = hm.keySet();
System.out.println (hm.get(101));}} 26
Benefits of Java Collections Framework
The Java Collections Framework provides the following benefits:
27