0% found this document useful (0 votes)
30 views24 pages

Chapter 4 Java Collections

The document discusses Java collections frameworks and interfaces. It provides 3 key points: 1) Collections frameworks provide common interfaces and implementations for collections to increase performance, reduce programming effort and provide interoperability. 2) The Java collections framework includes collection interfaces like Set, List and Map; implementation classes; and utility functions for manipulating collections. 3) Specific collection interfaces like Set, List and Map are discussed along with common implementation classes like HashSet, LinkedHashSet and TreeSet that implement different data structures.

Uploaded by

neakuto.diriba12
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
30 views24 pages

Chapter 4 Java Collections

The document discusses Java collections frameworks and interfaces. It provides 3 key points: 1) Collections frameworks provide common interfaces and implementations for collections to increase performance, reduce programming effort and provide interoperability. 2) The Java collections framework includes collection interfaces like Set, List and Map; implementation classes; and utility functions for manipulating collections. 3) Specific collection interfaces like Set, List and Map are discussed along with common implementation classes like HashSet, LinkedHashSet and TreeSet that implement different data structures.

Uploaded by

neakuto.diriba12
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 24

Chapter 4

Java Collections
Collections Frameworks
•A collection is an object that represents a
group of objects

•A collections framework is a unified


architecture for representing and manipulating
collections
- the manipulation should be independent of the
implementation details

•Advantages of having a collections framework


- reduces programming effort by providing useful data
structures and algorithms
- increases performance by providing high-performance data
structures and algorithms
- interoperability between the different collections
- Having a common language for manipulating the collections

Compiled by Tsegay M. 2
The components of Java Collections Framework
from the user’s perspective
• Collection Interfaces: form the basis of the
framework
- such as sets, lists and maps

• Implementations Classes: implementations of the


collection interfaces

• Utilities - Utility functions for manipulating


collections such as sorting, searching…

• The Java Collections Framework also includes:


- algorithms
- wrapper implementations
- add functionality to other implementations such as
synchronization
Compiled by Tsegay M. 3
Collections Interfaces
•Java allows Collection
Map
using:
• Lists
ArrayList, SortedMap
LinkedList Set List
• Sets
HashSet, TreeSet
• Maps SortedSet

HashMap, TreeMap

Compiled by Tsegay M. 4
Java
Collections
Object
(java.lang)

Collection Map

AbstractCollection AbstractMap
List Set

Dictionary

AbstractList AbstractSet
Map
HashMap

AbstractSequentialList Hashtable
HashSet
LinkedHashMap
ArrayList
SortedMap
LinkedHashSet SortedSet

LinkedList
TreeMap

Vector TreeSet

Stack

Compiled by Tsegay M. 5
Interface: Collection
• The Collection interface public interface Collection {
is the root of the // Basic Operations
collection hierarchy int size();
boolean isEmpty();
boolean contains(Object element);
• Some Collection boolean add(Object element);
implementations allow boolean remove(Object element);
- duplicate elements and Iterator iterator();
others do not
- the elements to be // Bulk Operations
ordered or not boolean containsAll(Collection c);
boolean addAll(Collection c);
boolean removeAll(Collection c);
• JDK doesn't provide any boolean retainAll(Collection c);
direct implementations of void clear();
this interface
- It provides implementations // Array Operations
of more specific sub Object[] toArray();
interfaces like Set and Object[] toArray(Object a[]);
List }

Compiled by Tsegay M. 6
Compiled by Tsegay M. 7
Interface: Set public interface Set {
// Basic Operations
• A Set is a collection int size();
boolean isEmpty();
that cannot contain boolean contains(Object
duplicate elements element);
boolean add(Object element);

• A set is not ordered boolean remove(Object


element);
- however, some subsets Iterator iterator();
maintain order using
extra data structures // Bulk Operations
boolean containsAll(Collection
c);
• This is similar to the boolean addAll(Collection c);
mathematical concept
boolean removeAll(Collection
of sets c);
boolean retainAll(Collection
c);
void clear();
Set<data-type> s1 = new HashSet<data-
• Set can be type>();
// Array Operations
Set<data-type> s2 = new
instantiated as: Object[] toArray();
LinkedHashSet<data-type>();
Object[] toArray(Object a[]);
Set<data-type> s3 = new TreeSet<data-
}
type>();
Compiled by Tsegay M. 8
Java Sets: HashSet
• HashSet uses a hash table as
the data structure to
Collection

represent a set
• HashSet is a good choice for AbstractCollection

representing sets if order Set

of the elements is not


important
import java.util.*;
AbstractSet

public methods
• HashSet class TestJavaCollection7{
are not synchronized
public static void main(String
args[]){
//Creating HashSet and adding HashSet
elements
HashSet<String> set=new
HashSet<String>(); LinkedHashSet SortedSet
set.add("Ravi");
set.add("Vijay");
set.add("Ravi"); TreeSet
set.add("Ajay");
//Traversing elements
Iterator<String>
itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());Compiled by Tsegay M. 9
} } }
Java Sets: LinkedHashSet
Collection
• Hash table and linked list
implementation of the Set
interface AbstractCollection
• LinkedHashSet differs from
Set
HashSet in that the order is
maintained
• Performance is below that of AbstractSet

HashSet, due to the expense of


import java.util.*;
maintaining
public the linked list
class TestJavaCollection8{
• public
Its methods
static are
void not
main(String
synchronized
args[]){ HashSet

LinkedHashSet<String> set=new
LinkedHashSet<String>();
set.add("Ravi"); LinkedHashSet SortedSet
set.add("Vijay");
set.add("Ravi");
set.add("Ajay"); TreeSet
Iterator<String>
itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Compiled by Tsegay M. 10
Java Sets: TreeSet
• Stores the elements in a
balanced binary tree Collection

- A binary tree is a tree in


which each node has at most
two children AbstractCollection

• TreeSet elements are sorted Set


• Less efficient than HashSet
in insertion due to the use
of a binary tree AbstractSet
import java.util.*;
• Its public
methods are
class not
TestJavaCollection9{
synchronized
public static void main(String
args[]){
//Creating and adding elements HashSet

TreeSet<String> set=new
TreeSet<String>();
set.add("Ravi"); LinkedHashSet SortedSet
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
TreeSet
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Compiled by Tsegay M. 11
Interface: List public interface List extends Collection {
// Positional Access
Object get(int index);
Object set(int index, Object element);
• A List is ordered void add(int index, Object element);
(also called a Object remove(int index);
abstract boolean addAll(int index,
sequence) Collection c);
• Lists can contain
// Search
duplicate elements int indexOf(Object o);
int lastIndexOf(Object o);
• List interface is
implemented by the // Iteration
ListIterator listIterator();
classes ArrayList, ListIterator listIterator(int index);
LinkedList, Vector,
// Range-view
and Stack. List subList(int from, int to);
}
• The user can access
elements by their
integer index
(position)
• To instantiate the
List interface, we
must use :

Compiled by Tsegay M. 12
Collection

Java Lists: ArrayList


AbstractCollection
• Uses an array to store
List

the elements AbstractList

• In addition to the
methods of the interface AbstractSequentialList

List ArrayList

• it provides methods to
manipulate the size of the
LinkedList Vector

array (e.g. ensureCapacity)


import java.util.*; Stack

• More efficient than class TestJavaCollection1{


public static void main(String args[])
LinkedList for methods
{
involving indices – ArrayList<String> list=new
ArrayList<String>();//Creating
get(), set() arraylist
list.add("Ravi");//Adding object in
• It is not synchronized
arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Compiled by Tsegay M. 13
Java Lists: LinkedList
• Java uses a doubly-linked list
- it can be traversed from the
beginning or the end

• LinkedList provides methods to


get, remove and insert an
element at the beginning and
end of the list
- these operations allow a linked
list to be used as a stack or a
queue

• LinkedList is not synchronized


- problems if multiple threads
access a list concurrently
- LinkedList must be synchronized
externally

Compiled by Tsegay M. 14
Java Lists: Vector
Collection

• Same as an the class


ArrayList List
AbstractCollection

• The main difference is AbstractList

that:
- The
import methods of Vector are
java.util.*;
publicsynchronized
class AbstractSequentialList

TestJavaCollection3{
public static void main(String ArrayList

args[]){
Vector<String> v=new
Vector<String>(); LinkedList Vector

v.add("Ayush");
v.add("Amit"); Stack
v.add("Ashish");
v.add("Garima");
Iterator<String>
itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } } Compiled by Tsegay M. 15
Java Lists: Stack
• The Stack class represents a
Collection

last-in-first-out (LIFO) stack


of objects
• The common push and pop List
AbstractCollection

operations are provided


• As well as a method to peek at
the top java.util.*;
import item on the stack is AbstractList
also provided
public class TestJavaCollection4{

public static void main(String AbstractSequentialList


args[]){
Stack<String> stack = new ArrayList
Stack<String>();
stack.push("Ayush");
stack.push("Garvit"); LinkedList Vector
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima"); Stack

stack.pop();
Iterator<String>
itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Compiled by Tsegay M. 16
} } }
public interface Map {
// Basic Operations
Interface: Map Object put(Object key, Object
value);
Object get(Object key);
• A Map is an object Object remove(Object key);
that maps keys to boolean containsKey(Object
values key);
boolean containsValue(Object
value);
int size();
• Maps cannot contain
boolean isEmpty();
duplicate keys
// Bulk Operations
void putAll(Map t);
• Each key can map to void clear();
at most one value
// Collection Views
public Set keySet();
public Collection values();
• Hashtables are an public Set entrySet();
example of Maps
// Interface for entrySet
elements
public interface Entry {
Object getKey();
Object getValue();
Object
Compiled by TsegaysetValue(Object
M. 17
value);
Interface: Map Hierarchy

There are two


interfaces for
implementing Map in
java: Map and
SortedMap, and three
classes: HashMap,
LinkedHashMap, and
TreeMap

Compiled by Tsegay M. 18
Interface: Map

Compiled by Tsegay M. 19
Java Maps: HashMap
• Contains values
based on the key.
• Contains only
unique keys.
• May have one null
key and multiple
null values
• Maintains no order
• Efficient in
inserting (put())
and retrieving
elements (get())

Compiled by Tsegay M. 20
Remove elements
Java HashMap Example
add elements import java.util.*;
public class HashMap2 {
import java.util.*;
public static void main(String
public class HashMapExample1{
args[]) {
HashMap<Integer,String> map=new
public static void
HashMap<Integer,String>();
main(String args[]){
map.put(100,"Amit");
HashMap<Integer,String>
map.put(101,"Vijay");
map=new
map.put(102,"Rahul");
HashMap<Integer,String>();//C
map.put(103, "Gaurav");
reating HashMap
System.out.println("Initial list of
map.put(1,"Mango"); //Put
elements: "+map);
elements in Map
//key-based removal
map.put(2,"Apple");
map.remove(100);
map.put(3,"Banana");
System.out.println("Updated list of
map.put(4,"Grapes");
elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Iterating
System.out.println("Updated list
Hashmap...");
of elements: "+map);
for(Map.Entry m :
//key-value pair based removal
map.entrySet()){
map.remove(102, "Rahul");
System.out.println("Updated list
System.out.println(m.getKey()
of elements: "+map);
+" "+m.getValue());
} }
} Compiled by Tsegay M. 21
}
Java Maps: TreeMap
• Red-Black tree based
Map

implementation of the
SortedMap interface
AbstractMap

• The keys are sorted


according to their HashMap

natural order (maintain


insertion order) LinkedHashMap

SortedMap

• Less efficient than


HashMap for insertion TreeMap

and mapping

• Cannot have a null key


but can have multiple
null values. Compiled by Tsegay M. 22
Remove elements
Java TreeMap Example
import java.util.*;
add elements public class TreeMap2 {
public static void main(String
import java.util.*; args[]) {
class TreeMap1{ TreeMap<Integer,String> map=new
public static void TreeMap<Integer,String>();
main(String args[]){ map.put(100,"Amit");
TreeMap<Integer,String> map.put(102,"Ravi");
map=new map.put(101,"Vijay");
TreeMap<Integer,String>(); map.put(103,"Rahul");
System.out.println("Before invoking
map.put(100,"Amit"); remove() method");
for(Map.Entry m:map.entrySet())
map.put(102,"Ravi"); {

map.put(101,"Vijay"); System.out.println(m.getKey()+"
"+m.getValue());
map.put(103,"Rahul"); }
map.remove(102);
System.out.println("After invoking
for(Map.Entry remove() method");
m:map.entrySet()){ for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey
()+" "+m.getValue()); System.out.println(m.getKey()+"
} "+m.getValue());
Compiled by Tsegay M. 23
}
The Iterator Interface
• JCF provides a uniform way to iterate through the
collection elements using the Iterator Interface

• The Iterator interface contains the following


methods
- boolean hasNext(): returns true if the iteration has more
elements.
- Object next(): returns the next element in the iteration.
- void remove(): removes from the collection the last element
returned by the iterator

• Iterator replaces Enumeration in the Java


Collections Framework. Iterators differ from
enumerations in two ways:
- They allow the caller to remove elements from the
collection during the iteration with well-defined semantics
(a major drawback of Enumerations)
- Method names have been improved

Compiled by Tsegay M. 24

You might also like