SlideShare a Scribd company logo
Java Collections
Javeed
APIs and Versions
• Number one hint for programming with
Java Collections: use the API
– http://java.sun.com/j2se/1.5.0/docs/api/java/util/Co
• Be sure to use the 1.5.0 APIs to get the
version with generics
Java Collections Framework
• The Java language API provides many of
the data structures from this class for you.
• It defines a “collection” as “an object that
represents a group of objects”.
• It defines a collections framework as “a
unified architecture for representing and
manipulating collections, allowing them to
be manipulated independent of the details
of their representation.”
Collections Framework (cont)
• Collection Interfaces - Represent different types of collections, such as sets, lists
and maps. These interfaces form the basis of the framework.
• General-purpose Implementations - Primary implementations of the collection
interfaces.
• Legacy Implementations - The collection classes from earlier releases, Vector and
Hashtable, have been retrofitted to implement the collection interfaces.
• Wrapper Implementations - Add functionality, such as synchronization, to other
implementations.
• Convenience Implementations - High-performance "mini-implementations" of the
collection interfaces.
• Abstract Implementations - Partial implementations of the collection interfaces to
facilitate custom implementations.
• Algorithms - Static methods that perform useful functions on collections, such as
sorting a list.
• Infrastructure - Interfaces that provide essential support for the collection interfaces.
• Array Utilities - Utility functions for arrays of primitives and reference objects. Not,
strictly speaking, a part of the Collections Framework, this functionality is being added
to the Java platform at the same time and relies on some of the same infrastructure.
Collection interfaces
• The core collection interfaces encapsulate
different types of collections. They
represent the abstract data types that are
part of the collections framework. They
are interfaces so they do not provide an
implementation!
public interface Collection<E>
extends Iterable<E>
• Collection — the root of the collection hierarchy. A
collection represents a group of objects known as its
elements. The Collection interface is the least common
denominator that all collections implement and is used to
pass collections around and to manipulate them when
maximum generality is desired. Some types of
collections allow duplicate elements, and others do not.
Some are ordered and others are unordered. The Java
platform doesn't provide any direct implementations of
this interface but provides implementations of more
specific subinterfaces, such as Set and List.
public interface Collection<E>
extends Iterable<E>
 public interface Collection<E> extends Iterable<E> {
    // Basic operations
    int size();
    boolean isEmpty();
    boolean contains(Object element);
    boolean add(E element);         //optional
    boolean remove(Object element); //optional
    Iterator<E> iterator();
    // Bulk operations
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c); //optional
    boolean removeAll(Collection<?> c);        //optional
    boolean retainAll(Collection<?> c);        //optional
    void clear();                              //optional
    // Array operations
    Object[] toArray();
    <T> T[] toArray(T[] a);
}
A note on iterators
• An Iterator is an object that enables you to traverse
through a collection and to remove elements from the
collection selectively, if desired. You get an Iterator
for a collection by calling its iterator() method. The
following is the Iterator interface.
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}
public interface Set<E>
extends Collection<E>
• Set — a collection that cannot contain
duplicate elements. This interface models
the mathematical set abstraction and is
used to represent sets, such as the cards
comprising a poker hand, the courses
making up a student's schedule, or the
processes running on a machine.
public interface Set<E>
extends Collection<E>
public interface Set<E> extends Collection<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Note: nothing added to Collection interface – except no duplicates allowed
public interface List<E>
extends Collection<E>
• List — an ordered collection (sometimes
called a sequence). Lists can contain
duplicate elements. The user of a List
generally has precise control over where
in the list each element is inserted and
can access elements by their integer index
(position). If you've used Vector, you're
familiar with the general flavor of List.
public interface List<E>
extends Collection<E>
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view
List<E> subList(int from, int to);
}
A note on ListIterators
• The three methods that ListIterator inherits from Iterator (hasNext, next, and remove)
do exactly the same thing in both interfaces. The hasPrevious and the previous
operations are exact analogues of hasNext and next. The former operations refer to
the element before the (implicit) cursor, whereas the latter refer to the element after
the cursor. The previous operation moves the cursor backward, whereas next moves
it forward.
• The nextIndex method returns the index of the element that would be returned by a
subsequent call to next, and previousIndex returns the index of the element that
would be returned by a subsequent call to previous
• The set method overwrites the last element returned by next or previous with the
specified element.
• The add method inserts a new element into the list immediately before the current
cursor position.
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
public interface Queue<E>
extends Collection<E>
• Queue — a collection used to hold
multiple elements prior to processing.
Besides basic Collection operations, a
Queue provides additional insertion,
extraction, and inspection operations.
public interface Queue<E>
extends Collection<E>
public interface Queue<E> extends
Collection<E> {
E element(); //throws
E peek(); //null
boolean offer(E e); //add - bool
E remove(); //throws
E poll(); //null
}
public interface Map<K,V>
• Map — an object that maps keys to
values. A Map cannot contain duplicate
keys; each key can map to at most one
value. If you've used Hashtable, you're
already familiar with the basics of Map.
public interface Map<K,V>
public interface Map<K,V> {
// Basic operations
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk operations
void putAll(Map<? extends K, ? extends V> m);
void clear();
// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();
// Interface for entrySet elements
public interface Entry {
K getKey();
V getValue();
V setValue(V value);
}
}
public interface SortedSet<E>
extends Set<E>
• SortedSet — a Set that maintains its
elements in ascending order. Several
additional operations are provided to take
advantage of the ordering. Sorted sets are
used for naturally ordered sets, such as
word lists and membership rolls.
public interface SortedSet<E>
extends Set<E>
public interface SortedSet<E> extends Set<E> {
// Range-view
SortedSet<E> subSet(E fromElement, E toElement);
SortedSet<E> headSet(E toElement);
SortedSet<E> tailSet(E fromElement);
// Endpoints
E first();
E last();
// Comparator access
Comparator<? super E> comparator();
}
Note on Comparator interface
• Comparator is another interface (in
addition to Comparable) provided by the
Java API which can be used to order
objects.
• You can use this interface to define an
order that is different from the Comparable
(natural) order.
public interface SortedMap<K,V>
extends Map<K,V>
• SortedMap — a Map that maintains its
mappings in ascending key order. This is
the Map analog of SortedSet. Sorted
maps are used for naturally ordered
collections of key/value pairs, such as
dictionaries and telephone directories.
public interface SortedMap<K,V>
extends Map<K,V>
public interface SortedMap<K, V> extends Map<K, V>{
SortedMap<K, V> subMap(K fromKey, K toKey);
SortedMap<K, V> headMap(K toKey);
SortedMap<K, V> tailMap(K fromKey);
K firstKey();
K lastKey();
Comparator<? super K> comparator();
}
General-purpose Implementations
Interfaces Implementations
  Hash table Resizable array
Tree
(sorted)
Linked list Hash table + Linked list
Set HashSet  
TreeSet
(sorted)
  LinkedHashSet
List   ArrayList  
LinkedList
 
Queue          
Map HashMap  
TreeMap
(sorted)
  LinkedHashMap
Note the naming convention
LinkedList also implements queue and there is a PriorityQueue implementation (implemented with heap)
implementations
• Each of the implementations offers the strengths
and weaknesses of the underlying data
structure.
• What does that mean for:
– Hashtable
– Resizable array
– Tree
– LinkedList
– Hashtable plus LinkedList
• Think about these tradeoffs when selecting
the implementation!
Choosing the datatype
• When you declare a Set, List or Map, you should use Set, List or Map
interface as the datatype instead of the implementing class. That will allow
you to change the implementation by changing a single line of code!
-----------------------------------------------------------------------------------------
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> ss = new LinkedHashSet<String>();
for (int i = 0; i < args.length; i++)
ss.add(args[i]);
Iterator i = ss.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
import java.util.*;
public class Test {
public static void main(String[] args)
{
//map to hold student grades
Map<String, Integer> theMap = new HashMap<String, Integer>();
theMap.put("Korth, Evan", 100);
theMap.put("Plant, Robert", 90);
theMap.put("Coyne, Wayne", 92);
theMap.put("Franti, Michael", 98);
theMap.put("Lennon, John", 88);
System.out.println(theMap);
System.out.println("--------------------------------------");
System.out.println(theMap.get("Korth, Evan"));
System.out.println(theMap.get("Franti, Michael"));
}
}
Other implementations in the API
• Wrapper implementations delegate all their real
work to a specified collection but add (or
remove) extra functionality on top of what the
collection offers.
– Synchronization Wrappers
– Unmodifiable Wrappers
• Convenience implementations are mini-
implementations that can be more convenient
and more efficient than general-purpose
implementations when you don't need their full
power
– List View of an Array
– Immutable Multiple-Copy List
– Immutable Singleton Set
– Empty Set, List, and Map Constants
Set
SortedSet
AbstractSet
Collection
TreeSet
HashSet
List AbstractList
AbstractSequentialList
ArrayList
LinkedList
AbstractCollection
Vector Stack
LinkedHashSet
Interfaces Abstract Classes Concrete Classes
Copyright: Liang
SortedMap
Map
TreeMap
HashMapAbstractMap
LinkedHashMap
Interfaces Abstract Classes Concrete Classes
Making your own implementations
• Most of the time you can use the
implementations provided for you in the
Java API.
• In case the existing implementations do
not satisfy your needs, you can write your
own by extending the abstract classes
provided in the collections framework.
algorithms
• The collections framework also provides polymorphic
versions of algorithms you can run on collections.
– Sorting
– Shuffling
– Routine Data Manipulation
• Reverse
• Fill copy
• etc.
– Searching
• Binary Search
– Composition
• Frequency
• Disjoint
– Finding extreme values
• Min
• Max

More Related Content

What's hot (20)

PDF
Collections Api - Java
Drishti Bhalla
 
PPT
Collection Framework in java
CPD INDIA
 
PDF
5 collection framework
Minal Maniar
 
PDF
Collections Java e Google Collections
André Faria Gomes
 
PDF
Java Collection framework
ankitgarg_er
 
PPT
Java Collections Framework
Sony India Software Center
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPT
Java collections concept
kumar gaurav
 
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
PPTX
Collections framework in java
yugandhar vadlamudi
 
PPTX
collection framework in java
MANOJ KUMAR
 
PPT
JAVA Collections frame work ppt
Ranjith Alappadan
 
PPTX
Java.util
Ramakrishna kapa
 
PPTX
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
PPSX
Collections - Lists, Sets
Hitesh-Java
 
PDF
Java Collections Framework
guestd8c458
 
DOCX
Java collections notes
Surendar Meesala
 
PPT
Java collection
Deepak Kumar
 
Collections Api - Java
Drishti Bhalla
 
Collection Framework in java
CPD INDIA
 
5 collection framework
Minal Maniar
 
Collections Java e Google Collections
André Faria Gomes
 
Java Collection framework
ankitgarg_er
 
Java Collections Framework
Sony India Software Center
 
Collections in Java Notes
Shalabh Chaudhary
 
Java collections concept
kumar gaurav
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Collections framework in java
yugandhar vadlamudi
 
collection framework in java
MANOJ KUMAR
 
JAVA Collections frame work ppt
Ranjith Alappadan
 
Java.util
Ramakrishna kapa
 
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
Collections - Lists, Sets
Hitesh-Java
 
Java Collections Framework
guestd8c458
 
Java collections notes
Surendar Meesala
 
Java collection
Deepak Kumar
 

Viewers also liked (13)

ODP
Preparing Java 7 Certifications
Giacomo Veneri
 
PPTX
Java: Collections
Arthur Emanuel
 
PPTX
Java simple programs
VEERA RAGAVAN
 
DOC
Advance java practicalty bscit sem5
ashish singh
 
PDF
Java collections the force awakens
RichardWarburton
 
PDF
Java Simple Programs
Upender Upr
 
PPTX
Introduction to Java Programming
One97 Communications Limited
 
PPT
Ch01 basic-java-programs
James Brotsos
 
PDF
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PPT
Simple Java Programs
AravindSankaran
 
PPT
Most Asked Java Interview Question and Answer
TOPS Technologies
 
PDF
Advanced Java Practical File
Soumya Behera
 
PPT
Introduction to-programming
BG Java EE Course
 
Preparing Java 7 Certifications
Giacomo Veneri
 
Java: Collections
Arthur Emanuel
 
Java simple programs
VEERA RAGAVAN
 
Advance java practicalty bscit sem5
ashish singh
 
Java collections the force awakens
RichardWarburton
 
Java Simple Programs
Upender Upr
 
Introduction to Java Programming
One97 Communications Limited
 
Ch01 basic-java-programs
James Brotsos
 
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Simple Java Programs
AravindSankaran
 
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Advanced Java Practical File
Soumya Behera
 
Introduction to-programming
BG Java EE Course
 
Ad

Similar to java collections (20)

PPT
JavaCollections.ppt
Irfanhabeeb18
 
PPT
JavaCollections.ppt
boopathirajaraja1
 
PPT
Best core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
PPTX
Java collections
anshkhurana7
 
PPTX
oop lecture framework,list,maps,collection
ssuseredfbe9
 
PPT
Collections
Rajkattamuri
 
PPT
Collections
Manav Prasad
 
PPTX
Java Collections Framework - Interfaces, Classes and Algorithms
RajalakshmiS74
 
PPTX
LJ_JAVA_FS_Collection.pptx
Raneez2
 
PDF
javacollections.pdf
ManojKandhasamy1
 
PPTX
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
PPTX
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
PPTX
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
PPTX
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
PPTX
Collections Training
Ramindu Deshapriya
 
PPT
Collection Framework.power point presentation.......
Betty333100
 
PDF
Collections and generics
Muthukumaran Subramanian
 
PPT
Collection framework
DilvarSingh2
 
PDF
java unit 4 pdf - about java collections
aapalaks
 
PPT
description of Collections, seaching & Sorting
mdimberu
 
JavaCollections.ppt
Irfanhabeeb18
 
JavaCollections.ppt
boopathirajaraja1
 
Best core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
Java collections
anshkhurana7
 
oop lecture framework,list,maps,collection
ssuseredfbe9
 
Collections
Rajkattamuri
 
Collections
Manav Prasad
 
Java Collections Framework - Interfaces, Classes and Algorithms
RajalakshmiS74
 
LJ_JAVA_FS_Collection.pptx
Raneez2
 
javacollections.pdf
ManojKandhasamy1
 
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
Collections Training
Ramindu Deshapriya
 
Collection Framework.power point presentation.......
Betty333100
 
Collections and generics
Muthukumaran Subramanian
 
Collection framework
DilvarSingh2
 
java unit 4 pdf - about java collections
aapalaks
 
description of Collections, seaching & Sorting
mdimberu
 
Ad

More from javeed_mhd (20)

PPTX
For each component in mule
javeed_mhd
 
PPTX
Filter expression in mule
javeed_mhd
 
PPTX
File component in mule
javeed_mhd
 
PPTX
Database component in mule
javeed_mhd
 
PPTX
Choice component in mule
javeed_mhd
 
PPTX
Vm component in mule
javeed_mhd
 
PPTX
Until successful component in mule
javeed_mhd
 
PPTX
Quartz component in mule
javeed_mhd
 
PPTX
Mule management console installation
javeed_mhd
 
PPTX
Mule esb made system integration easy
javeed_mhd
 
PPTX
Message properties component in mule
javeed_mhd
 
PPTX
Junit in mule demo
javeed_mhd
 
PPTX
How to install sonarqube plugin in anypoint
javeed_mhd
 
PPTX
How to commit a project in svn using svn plugin in anypointstudio
javeed_mhd
 
PPTX
Mapping and listing with mule
javeed_mhd
 
PPT
Mule any point exchange
javeed_mhd
 
PPT
Mule esb api layer
javeed_mhd
 
PDF
Mule Maven Plugin
javeed_mhd
 
PPTX
Mule esb stripe
javeed_mhd
 
PPTX
Mule with stored procedure
javeed_mhd
 
For each component in mule
javeed_mhd
 
Filter expression in mule
javeed_mhd
 
File component in mule
javeed_mhd
 
Database component in mule
javeed_mhd
 
Choice component in mule
javeed_mhd
 
Vm component in mule
javeed_mhd
 
Until successful component in mule
javeed_mhd
 
Quartz component in mule
javeed_mhd
 
Mule management console installation
javeed_mhd
 
Mule esb made system integration easy
javeed_mhd
 
Message properties component in mule
javeed_mhd
 
Junit in mule demo
javeed_mhd
 
How to install sonarqube plugin in anypoint
javeed_mhd
 
How to commit a project in svn using svn plugin in anypointstudio
javeed_mhd
 
Mapping and listing with mule
javeed_mhd
 
Mule any point exchange
javeed_mhd
 
Mule esb api layer
javeed_mhd
 
Mule Maven Plugin
javeed_mhd
 
Mule esb stripe
javeed_mhd
 
Mule with stored procedure
javeed_mhd
 

Recently uploaded (20)

PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Survival Models: Proper Scoring Rule and Stochastic Optimization with Competi...
Paris Women in Machine Learning and Data Science
 
PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Survival Models: Proper Scoring Rule and Stochastic Optimization with Competi...
Paris Women in Machine Learning and Data Science
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
Digital Circuits, important subject in CS
contactparinay1
 

java collections

  • 2. APIs and Versions • Number one hint for programming with Java Collections: use the API – http://java.sun.com/j2se/1.5.0/docs/api/java/util/Co • Be sure to use the 1.5.0 APIs to get the version with generics
  • 3. Java Collections Framework • The Java language API provides many of the data structures from this class for you. • It defines a “collection” as “an object that represents a group of objects”. • It defines a collections framework as “a unified architecture for representing and manipulating collections, allowing them to be manipulated independent of the details of their representation.”
  • 4. Collections Framework (cont) • Collection Interfaces - Represent different types of collections, such as sets, lists and maps. These interfaces form the basis of the framework. • General-purpose Implementations - Primary implementations of the collection interfaces. • Legacy Implementations - The collection classes from earlier releases, Vector and Hashtable, have been retrofitted to implement the collection interfaces. • Wrapper Implementations - Add functionality, such as synchronization, to other implementations. • Convenience Implementations - High-performance "mini-implementations" of the collection interfaces. • Abstract Implementations - Partial implementations of the collection interfaces to facilitate custom implementations. • Algorithms - Static methods that perform useful functions on collections, such as sorting a list. • Infrastructure - Interfaces that provide essential support for the collection interfaces. • Array Utilities - Utility functions for arrays of primitives and reference objects. Not, strictly speaking, a part of the Collections Framework, this functionality is being added to the Java platform at the same time and relies on some of the same infrastructure.
  • 5. Collection interfaces • The core collection interfaces encapsulate different types of collections. They represent the abstract data types that are part of the collections framework. They are interfaces so they do not provide an implementation!
  • 6. public interface Collection<E> extends Iterable<E> • Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List.
  • 7. public interface Collection<E> extends Iterable<E>  public interface Collection<E> extends Iterable<E> {     // Basic operations     int size();     boolean isEmpty();     boolean contains(Object element);     boolean add(E element);         //optional     boolean remove(Object element); //optional     Iterator<E> iterator();     // Bulk operations     boolean containsAll(Collection<?> c);     boolean addAll(Collection<? extends E> c); //optional     boolean removeAll(Collection<?> c);        //optional     boolean retainAll(Collection<?> c);        //optional     void clear();                              //optional     // Array operations     Object[] toArray();     <T> T[] toArray(T[] a); }
  • 8. A note on iterators • An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator() method. The following is the Iterator interface. public interface Iterator<E> {     boolean hasNext();     E next();     void remove(); //optional }
  • 9. public interface Set<E> extends Collection<E> • Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine.
  • 10. public interface Set<E> extends Collection<E> public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array Operations Object[] toArray(); <T> T[] toArray(T[] a); } Note: nothing added to Collection interface – except no duplicates allowed
  • 11. public interface List<E> extends Collection<E> • List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List.
  • 12. public interface List<E> extends Collection<E> public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); //optional boolean add(E element); //optional void add(int index, E element); //optional E remove(int index); //optional boolean addAll(int index, Collection<? extends E> c); //optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); // Range-view List<E> subList(int from, int to); }
  • 13. A note on ListIterators • The three methods that ListIterator inherits from Iterator (hasNext, next, and remove) do exactly the same thing in both interfaces. The hasPrevious and the previous operations are exact analogues of hasNext and next. The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the element after the cursor. The previous operation moves the cursor backward, whereas next moves it forward. • The nextIndex method returns the index of the element that would be returned by a subsequent call to next, and previousIndex returns the index of the element that would be returned by a subsequent call to previous • The set method overwrites the last element returned by next or previous with the specified element. • The add method inserts a new element into the list immediately before the current cursor position. public interface ListIterator<E> extends Iterator<E> { boolean hasNext(); E next(); boolean hasPrevious(); E previous(); int nextIndex(); int previousIndex(); void remove(); //optional void set(E e); //optional void add(E e); //optional }
  • 14. public interface Queue<E> extends Collection<E> • Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
  • 15. public interface Queue<E> extends Collection<E> public interface Queue<E> extends Collection<E> { E element(); //throws E peek(); //null boolean offer(E e); //add - bool E remove(); //throws E poll(); //null }
  • 16. public interface Map<K,V> • Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hashtable, you're already familiar with the basics of Map.
  • 17. public interface Map<K,V> public interface Map<K,V> { // Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk operations void putAll(Map<? extends K, ? extends V> m); void clear(); // Collection Views public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet(); // Interface for entrySet elements public interface Entry { K getKey(); V getValue(); V setValue(V value); } }
  • 18. public interface SortedSet<E> extends Set<E> • SortedSet — a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.
  • 19. public interface SortedSet<E> extends Set<E> public interface SortedSet<E> extends Set<E> { // Range-view SortedSet<E> subSet(E fromElement, E toElement); SortedSet<E> headSet(E toElement); SortedSet<E> tailSet(E fromElement); // Endpoints E first(); E last(); // Comparator access Comparator<? super E> comparator(); }
  • 20. Note on Comparator interface • Comparator is another interface (in addition to Comparable) provided by the Java API which can be used to order objects. • You can use this interface to define an order that is different from the Comparable (natural) order.
  • 21. public interface SortedMap<K,V> extends Map<K,V> • SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.
  • 22. public interface SortedMap<K,V> extends Map<K,V> public interface SortedMap<K, V> extends Map<K, V>{ SortedMap<K, V> subMap(K fromKey, K toKey); SortedMap<K, V> headMap(K toKey); SortedMap<K, V> tailMap(K fromKey); K firstKey(); K lastKey(); Comparator<? super K> comparator(); }
  • 23. General-purpose Implementations Interfaces Implementations   Hash table Resizable array Tree (sorted) Linked list Hash table + Linked list Set HashSet   TreeSet (sorted)   LinkedHashSet List   ArrayList   LinkedList   Queue           Map HashMap   TreeMap (sorted)   LinkedHashMap Note the naming convention LinkedList also implements queue and there is a PriorityQueue implementation (implemented with heap)
  • 24. implementations • Each of the implementations offers the strengths and weaknesses of the underlying data structure. • What does that mean for: – Hashtable – Resizable array – Tree – LinkedList – Hashtable plus LinkedList • Think about these tradeoffs when selecting the implementation!
  • 25. Choosing the datatype • When you declare a Set, List or Map, you should use Set, List or Map interface as the datatype instead of the implementing class. That will allow you to change the implementation by changing a single line of code! ----------------------------------------------------------------------------------------- import java.util.*; public class Test { public static void main(String[] args) { Set<String> ss = new LinkedHashSet<String>(); for (int i = 0; i < args.length; i++) ss.add(args[i]); Iterator i = ss.iterator(); while (i.hasNext()) System.out.println(i.next()); } }
  • 26. import java.util.*; public class Test { public static void main(String[] args) { //map to hold student grades Map<String, Integer> theMap = new HashMap<String, Integer>(); theMap.put("Korth, Evan", 100); theMap.put("Plant, Robert", 90); theMap.put("Coyne, Wayne", 92); theMap.put("Franti, Michael", 98); theMap.put("Lennon, John", 88); System.out.println(theMap); System.out.println("--------------------------------------"); System.out.println(theMap.get("Korth, Evan")); System.out.println(theMap.get("Franti, Michael")); } }
  • 27. Other implementations in the API • Wrapper implementations delegate all their real work to a specified collection but add (or remove) extra functionality on top of what the collection offers. – Synchronization Wrappers – Unmodifiable Wrappers • Convenience implementations are mini- implementations that can be more convenient and more efficient than general-purpose implementations when you don't need their full power – List View of an Array – Immutable Multiple-Copy List – Immutable Singleton Set – Empty Set, List, and Map Constants
  • 28. Set SortedSet AbstractSet Collection TreeSet HashSet List AbstractList AbstractSequentialList ArrayList LinkedList AbstractCollection Vector Stack LinkedHashSet Interfaces Abstract Classes Concrete Classes Copyright: Liang SortedMap Map TreeMap HashMapAbstractMap LinkedHashMap Interfaces Abstract Classes Concrete Classes
  • 29. Making your own implementations • Most of the time you can use the implementations provided for you in the Java API. • In case the existing implementations do not satisfy your needs, you can write your own by extending the abstract classes provided in the collections framework.
  • 30. algorithms • The collections framework also provides polymorphic versions of algorithms you can run on collections. – Sorting – Shuffling – Routine Data Manipulation • Reverse • Fill copy • etc. – Searching • Binary Search – Composition • Frequency • Disjoint – Finding extreme values • Min • Max