0% found this document useful (0 votes)
23 views

Chapter 6

This prints the elements and size of a LinkedList containing continents.

Uploaded by

lencho03406
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Chapter 6

This prints the elements and size of a LinkedList containing continents.

Uploaded by

lencho03406
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter Six

Collection Frame Work

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

 Collections are used to store, retrieve, manipulate, and communicate aggregate


data.
4
Contd…
 Collection: The root of the collection hierarchy. A collection
represents a group of objects known as its elements. It is parent
of all collections framework.
 Set : A Set represents a group of elements (objects) arranged
just like an array. The set will grow dynamically when the
elements are stored into it. A set will not allow duplicate
elements.
 Sorted Set: Ordered version of the set interface.
 List:- Lists are like sets but allow duplicate values to be stored.
 Queue: Apart from following the FIFO (First In First Out)
principles this Collection offers variety of implementation.
 Map:- Maps store elements in the form of key value pairs. If
the key is provided its corresponding value can be obtained. It
does not allow duplicate keys.
 Sorted Map: Maintains ascending order of keys. 5
Collections
 A collection is an object which can store group of other objects.
• A collection object has a class called Collection class or
Container class.
• All the collection classes are available in the package called
'java.util’
• Group of collection classes is called a Collection Framework.
• A collection object does not store the physical copies of other
objects; it stores references of other objects.
• All the collection classes in java.util package are the
implementation classes of different interfaces.
 Some examples of collections are
• the cards you hold in a card game,
• your favorite songs stored in your computer,
• the members of a sports team

6
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();

 These methods are enough to define the basic behavior of


a collection
 Provides an Iterator to step through the elements in the
Collection

7
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

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

 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. 10
ArrayList Overview
 The ArrayList class extends AbstractList and implements the List
interface. ArrayList supports dynamic arrays that can grow as needed.
 Standard Java arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many
elements an array will hold.
 Array lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged. When objects are removed, the array may be
shrunk.
 The ArrayList class supports three constructors.
 The first constructor builds an empty array list: ArrayList( )
 The following constructor builds an array list that is initialized with the
elements of the collection c.
ArrayList(Collection c)
 The following constructor builds an array list that has the specified initial
capacity. The capacity is the size of the underlying array that is used to store
the elements. The capacity grows automatically as elements are added to an
array list.
11
ArrayList(int capacity)
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) 12


Example: ArrayList
Program that shows the use of ArrayList class.
import java.util.*;
class ArrayListDemo
{ public static void main(String args[])
{ ArrayList <String> al = new ArrayList<String>();
al.add (“Africa"); al.add ("North America");
al.add ("South America"); al.add (“Asia");
al.add ("Europe");
al.add (1,"Australia");
al.add (2,"Antarctica");
System.out.print("Size of the Array List is: " + al.size ());
System.out.print("\nRetrieving elements in ArrayList using Iterator:");
Iterator it = al.iterator ();
while (it.hasNext () )
System.out.print (it.next () + "\t"); }}
13
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

14
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()

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

HashSet TreeSet LinkedHashSet


17
HashSet
 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
18
if two objects are equal, they must have the same hashCode()
TreeSet
 Elements can be inserted in any order

 The TreeSet stores them in order

 An iterator always presents them in order

 Default order is defined by natural order

objects implement the Comparable interface

TreeSet uses compareTo(Object o) to sort elements

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

HashSet TreeSet Linked HashSet

Storage Type Hash Table Red-Black Tree Hash Table with a


Linked List

Performance Best performance Slower than Little costly than


HashSet HashSet

Order of Iteration No guarantee of Order based Orders elements


order of iteration based on insertion

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:

 Reduces programming effort

 Increases program speed and quality:

 Allows interoperability among unrelated APIs

 Reduces effort to learn and to use new APIs

 Fosters software reuse

27

You might also like