SlideShare a Scribd company logo
JAVA PROGRAMMING - The
Collections Framework
Dr R Jegadeesan Prof-CSE
Jyothishmathi Institute of Technology and Science,
Karimnagar
SYLLABUS
The Collections Framework (java.util)- Collections overview,
Collection Interfaces, The Collection classes- Array List, Linked
List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing
a Collection via an Iterator, Using an Iterator, The For-Each
alternative, Map Interfaces and Classes, Comparators,
Collection algorithms, Arrays, The Legacy Classes and
Interfaces- Dictionary, Hashtable ,Properties, Stack, Vector
More Utility classes, String Tokenizer, Bit Set, Date, Calendar,
Random, Formatter, Scanner
UNIT IV : COLLECTION FRAMEWORK
Topic Name : Introduction to Collection Framework
Topic : Introduction to Collection Framework
Aim & Objective : To make the student understand the concept of Collection
Interfaces and Collection Classes and Legacy Classes and Interfaces.
Application With Example :Java Program Using Collection Interfaces and Collection
Classes
Limitations If Any :
Reference Links :
• Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education
(India) Pvt. Ltd.
• https://www.javatpoint.com/collections-in-java
• Video Link details
• https://www.youtube.com/watch?v=v9zg9g_FbJY
Universities & Important Questions :
• What is the Collection framework in Java?
• What are the main differences between array and collection?
• Explain various interfaces used in Collection framework?
• What is the difference between ArrayList and Vector?
• What is the difference between ArrayList and LinkedList?
• What is the difference between Iterator and ListIterator?
• What is the difference between Iterator and Enumeration?
• What is the difference between List and Set?
• What does the hashCode() method?
• What is the Dictionary class?
▪ Collection Overview
▪ Collection Classes
▪ Collection Interfaces
▪ Legacy Classes
▪ Legacy Interfaces
UNIT – IV
CONTENTS
6
Collection Overview
• List<E> is a generic type (furthermore it’s a generic interface)
• ArrayList<E> is a generic class, which implements List<E>
public class ArrayList<E>
implements List<E> {
private E[] elementData;
private int size;
... //stuff
public boolean add(E o) {
elementData[size++] = o;
return true;
}
public E get(int i) {
return elementData[i];
} //etc...
}
E is a type variable/
type parameter
List<Money> list = new ArrayList<Money>();
List/ArrayList both
parameterised with Money
When you parameterise ArrayList<E>
with Money, think of it as:
E “becomes” Money
public class ArrayList
implements List<Money> {
private Money[] elementData;
private int size;
... //stuff
public boolean add(Money o) {
elementData[size++] = o;
return true;
}
public Money get(int i) {
return elementData[i];
} //etc...
}
7
More than just Lists…
• ArrayLists and LinkedLists are just two of the many classes
comprising the Java Collections Framework (JCF)
• A collection is an object that maintains references to others
objects
– Essentially a subset of data structures
• JCF forms part of the java.util package and provides:
– Interfaces
• Each defines the operations and contracts for a particular type of
collection (List, Set, Queue, etc)
• Idea: when using a collection object, it’s sufficient to know its interface
– Implementations
• Reusable classes that implement above interfaces (e.g. LinkedList,
HashSet)
– Algorithms
• Useful polymorphic methods for manipulating and creating objects
whose classes implement collection interfaces
• Sorting, index searching, reversing, replacing etc.
8
Interfaces
Root interface for operations
common to all types of collections
Specialises collection with
operations for FIFO and priority
queues.
Stores a sequence of elements,
allowing indexing methods
A special
Collection that
cannot contain
duplicates.
Special Set that retains
ordering of elements.
Stores mappings from
keys to values
Special map in
which keys are
ordered
Generalisation
Specialisation
Collection
Set List Queue
SortedSet
Map
SortedMap
9
Expansion of contracts
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int
+iterator():Iterator<E>
etc…
<<interface>>
Collection<E>
+add(E):boolean
+remove(Object):boolean
+get(int):E
+indexOf(Object):int
+contains(Object):boolean
+size():int
+iterator():Iterator<E>
etc…
<<interface>>
List<E>
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int
+iterator():Iterator<E>
etc…
<<interface>>
Set<E>
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int
+iterator():Iterator<E>
+first():E
+last():E
etc…
<<interface>>
SortedSet<E>
10
java.util.Iterator<E>
• Think about typical usage scenarios for Collections
– Retrieve the list of all patients
– Search for the lowest priced item
• More often than not you would have to traverse every element in
the collection – be it a List, Set, or your own datastructure
• Iterators provide a generic way to traverse through a collection
regardless of its implementation
a
f
g
d
b
c
e
i
h
a b c d e f g h i
a b c d e f g h i
Iterator
next():d
iterator()
iterator()
Set
List
hasNext()?
11
Using an Iterator
• Quintessential code snippet for collection iteration:
public void list(Collection<Item> items) {
Iterator<Item> it = items.iterator();
while(it.hasNext()) {
Item item = it.next();
System.out.println(item.getTitle());
}
}
+hasNext():boolean
+next():E
+remove():void
<<interface>>
Iterator<E>
Design notes:
Above method takes in an object whose class implements Collection
List, ArrayList, LinkedList, Set, HashSet, TreeSet, Queue, MyOwnCollection, etc
We know any such object can return an Iterator through method iterator()
We don’t know the exact implementation of Iterator we are getting, but we
don’t care, as long as it provides the methods next() and hasNext()
Good practice: Program to an interface!
12
java.lang.Iterable<T>
• This is called a “for-each” statement
– For each item in items
• This is possible as long as items is of type Iterable
– Defines single method iterator()
• Collection (and hence all its subinterfaces) implements
Iterable
• You can do this to your own implementation of Iterable
too!
– To do this you may need to return your own implementation
of Iterator
Iterator<Item> it = items.iterator();
while(it.hasNext()) {
Item item = it.next();
System.out.println(item);
}
for (Item item : items) {
System.out.println(item);
}
=
<<interface>>
Iterable<T>
+iterator():Iterator<T>
Collection<T> MyBag<T>
List<T>
Set<T>
etc
13
java.util.Collections
• Offers many very useful utilities and
algorithms for manipulating and creating
collections
– Sorting lists
– Index searching
– Finding min/max
– Reversing elements of a list
– Swapping elements of a list
– Replacing elements in a list
– Other nifty tricks
• Saves you having to implement
them yourself → reuse
14
Collections.sort()
• Java’s implementation of merge sort – ascending order
public static <T extends Comparable<? super T>> void sort(List<T> list)
1)
public static <T> void sort(List<T> list, Comparator<? super T> c)
2)
Translation:
1. Only accepts a List parameterised with type implementing Comparable
2. Accepts a List parameterised with any type as long as you also give it a
Comparator implementation that defines the ordering for that type
What types of objects can you sort? Anything that has an ordering
Two sort() methods: sort a given List according to either 1) natural
ordering of elements or an 2) externally defined ordering.
e b c d
0 1 2 3 4
b f
5 6
a a b b c
0 1 2 3 4
d e
5 6
f
     
15
java.lang.Comparable<T>
• A generic interface with a single method: int compareTo(T)
– Return 0 if this = other
– Return any +’ve integer if this > other
– Return any –’ve integer if this < other
• Implement this interface to define natural ordering on objects of type T
public class Money implements Comparable<Money> {
...
public int compareTo( Money other ) {
if( this.cents == other.cents ) {
return 0;
}
else if( this.cents < other.cents ) {
return -1;
}
else {
return 1;
}
}
A more concise way of doing this? (hint: 1 line)
return this.cents – other.cents;
m1 = new Money(100,0);
m2 = new Money(50,0);
m1.compareTo(m2) returns 1;
16
Natural-order sorting
List<Money> funds = new ArrayList<Money>();
funds.add(new Money(100,0));
funds.add(new Money(5,50));
funds.add(new Money(-40,0));
funds.add(new Money(5,50));
funds.add(new Money(30,0));
Collections.sort(funds);
System.out.println(funds);
List<CD> albums = new ArrayList<CD>();
albums.add(new CD("Street Signs","Ozomatli",2.80));
//etc...
Collections.sort(albums);
public static <T extends Comparable<? super T>> void sort(List<T> list)

What’s the output?
[-40.0,
5.50,
5.50,
30.0,
100.0]
CD does not implement a
Comparable interface
Wildcard (later)
17
java.util.Comparator<T>
• Useful if the type of elements to be sorted is not
Comparable, or you want to define an alternative ordering
• Also a generic interface that defines methods
compare(T,T) and equals(Object)
– Usually only need to define compare(T,T)
• Define ordering by CD’s getPrice() → Money
– Note: PriceComparator implements a Comparator para-
meterised with CD → T “becomes” CD
public class PriceComparator
implements Comparator<CD> {
public int compare(CD c1, CD c2) {
return c1.getPrice().compareTo(c2.getPrice());
}
}
+compare(T o1, T o2):int
+equals(Object other):boolean
<<interface>>
Comparator<T>
CD
+getTitle():String
+getArtist():String
+getPrice():Money
Comparator and Comparable
going hand in hand ☺
18
Comparator sorting
• Note, in sort(), Comparator overrides natural
ordering
– i.e. Even if we define natural ordering for CD, the given comparator is still going to
be used instead
– (On the other hand, if you give null as Comparator, then natural ordering is used)
List<CD> albums = new ArrayList<CD>();
albums.add(new CD("Street Signs","Ozomatli",new Money(3,50)));
albums.add(new CD("Jazzinho","Jazzinho",new Money(2,80)));
albums.add(new CD("Space Cowboy","Jamiroquai",new Money(5,00)));
albums.add(new CD("Maiden Voyage","Herbie Hancock",new Money(4,00)));
albums.add(new CD("Here's the Deal","Liquid Soul",new Money(1,00)));
Collections.sort(albums, new PriceComparator());
System.out.println(albums);
public static <T> void sort(List<T> list, Comparator<? super T> c)
implements Comparator<CD>
19
Set<E>
• Mathematical Set abstraction – contains no duplicate elements
– i.e. no two elements e1 and e2 such that e1.equals(e2)
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
+isEmpty():boolean
+size():int
+iterator():Iterator<E>
etc…
<<interface>>
Set<E>
remove(c)
→true
a
b
c
d
remove(x)
→false
add(x)
→true a b
c
d
x
add(b)
→false
contains(e)
→true
?
contains(x)
→false
a b
c
d
e
isEmpty()
→false
size()
→5
+first():E
+last():E
etc…
<<interface>>
SortedSet<E>
20
HashSet<E>
• Typically used implementation of Set.
• Hash? Implemented using HashMap (later)
• Parameterise Sets just as you parameterise Lists
• Efficient (constant time) insert, removal and contains
check – all done through hashing
• x and y are duplicates if x.equals(y)
• How are elements ordered? Quiz:
Set<String> words = new HashSet<String>();
words.add("Bats");
words.add("Ants");
words.add("Crabs");
words.add("Ants");
System.out.println(words.size());
for (String word : words) {
System.out.println(word);
}
?
a) Bats, Ants, Crabs
b) Ants, Bats, Crabs
c) Crabs, Bats, Ants
d) Nondeterministic
+add(E):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int
+iterator():Iterator<E>
etc…
<<interface>>
Set<E>
HashSet<E>
3
21
TreeSet<E> (SortedSet<E>)
• If you want an ordered set, use an implementation
of a SortedSet: TreeSet
• What’s up with “Tree”? Red-black tree
• Guarantees that all elements are ordered (sorted)
at all times
– add() and remove() preserve this condition
– iterator() always returns the elements in a
specified order
• Two ways of specifying ordering
– Ensuring elements have natural ordering (Comparable)
– Giving a Comparator<E> to the constructor
• Caution: TreeSet considers x and y are duplicates if
x.compareTo(y) == 0 (or compare(x,y) == 0)
+first():E
+last():E
etc…
<<interface>>
SortedSet<E>
TreeSet<E>
22
TreeSet construction
• String has a natural
ordering, so empty
constructor
Set<String> words = new TreeSet<String>();
words.add("Bats");
words.add("Ants");
words.add("Crabs");
for (String word : words) {
System.out.println(word);
}
Set<CD> albums = new TreeSet<CD>(new PriceComparator());
albums.add(new CD("Street Signs","O",new Money(3,50)));
albums.add(new CD("Jazzinho","J",new Money(2,80)));
albums.add(new CD("Space Cowboy","J",new Money(5,00)));
albums.add(new CD("Maiden Voyage","HH",new Money(4,00)));
albums.add(new CD("Here’s the Deal","LS",new Money(2,80)));
System.out.println(albums.size());
for (CD album : albums) {
System.out.println(album);
}
But CD doesn’t, so you must pass in a Comparator to the constructor
What’s the output?
4
Jazzinho; Street; Maiden; Space
What’s the output?
Ants; Bats; Crabs
23
Map<K,V>
• Stores mappings from (unique) keys (type K) to values (type V)
– See, you can have more than one type parameters!
• Think of them as “arrays” but with objects (keys) as indexes
– Or as “directories”: e.g. "Bob" → 021999887
+put(K,V):V
+get(Object):V
+remove(Object):V
+size():int
+keySet():Set<K>
+values():Collection<V>
etc…
<<interface>>
Map<K,V>
+firstKey():K
+lastKey():K
etc…
<<interface>>
SortedMap<K,V>
get(k)
→a a
b
c
b
k
m
p
n
get(x)
→null
keys values
put(x,e)
→null
a
b
c
b
k
m
p
n
e
x
put(k,f)
→a
a
b
c
b
k
m
p
n
f
size()
→4
remove(n)
→b
remove(x)
→null
a
b
c
b
k
m
p
n
keySet()
→Set
k
m p
n
values()
→Collection
a b
c b
24
HashMap<K,V>
• aka Hashtable (SE250)
• keys are hashed using Object.hashCode()
– i.e. no guaranteed ordering of keys
• keySet() returns a HashSet
• values() returns an unknown Collection
+put(K,V):V
+get(Object):V
+remove(Object):V
+size():int
+keySet():Set<K>
+values():Collection<V>
etc…
<<interface>>
Map<K,V>
HashMap<K,V>
Map<String, Integer> directory
= new HashMap<String, Integer>();
directory.put("Mum", new Integer(9998888));
directory.put("Dad", 9998888);
directory.put("Bob", 12345678);
directory.put("Edward", 5553535);
directory.put("Bob", 1000000);
System.out.println(directory.size());
for (String key : directory.keySet()) {
System.out.print(key+"'s number: ");
System.out.println(directory.get(key));
}
System.out.println(directory.values());
4 or 5?
Set<String>
“autoboxing”
What’s Bob’s number?
25
TreeMap<K,V>
• Guaranteed ordering of keys (like TreeSet)
– In fact, TreeSet is implemented using TreeMap ☺
– Hence keySet() returns a TreeSet
• values() returns an unknown Collection – ordering depends
on ordering of keys
+firstKey():K
+lastKey():K
etc…
<<interface>>
SortedMap<K,V>
TreeMap<K,V>
Map<String, Integer> directory
= new TreeMap<String, Integer>();
directory.put("Mum", new Integer(9998888));
directory.put("Dad", 9998888);
directory.put("Bob", 12345678);
directory.put("Edward", 5553535);
directory.put("Bob", 1000000);
System.out.println(directory.size());
for (String key : directory.keySet()) {
System.out.print(key+"'s #: ");
System.out.println(directory.get(key));
}
System.out.println(directory.values());
Loop output?
Bob's #: 1000000
Dad's #: 9998888
Edward's #: 5553535
Mum's #: 9998888
4
?
Empty constructor
→ natural ordering
26
TreeMap with Comparator
• As with TreeSet, another way of constructing TreeMap is to give a Comparator →
necessary for non-Comparable keys
Map<CD, Double> ratings
= new TreeMap<CD, Double>(new PriceComparator());
ratings.put(new CD("Street Signs","O",new Money(3,50)), 8.5);
ratings.put(new CD("Jazzinho","J",new Money(2,80)), 8.0);
ratings.put(new CD("Space Cowboy","J",new Money(5,00)), 9.0);
ratings.put(new CD("Maiden Voyage","H",new Money(4,00)), 9.5);
ratings.put(new CD("Here's the Deal","LS",new Money(2,80)), 9.0);
System.out.println(ratings.size());
for (CD key : ratings.keySet()) {
System.out.print("Rating for "+key+": ");
System.out.println(ratings.get(key));
}
System.out.println("Ratings: "+ratings.values());
4
Depends on
key ordering
Ordered by key’s
price
27
Thank you

More Related Content

What's hot

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
Data structures using C
Data structures using CData structures using C
Data structures using C
Prof. Dr. K. Adisesha
 
Standard template library
Standard template libraryStandard template library
Standard template library
Sukriti Singh
 

What's hot (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Standard template library
Standard template libraryStandard template library
Standard template library
 

Similar to JAVA PROGRAMMING - The Collections Framework

collections
collectionscollections
collections
javeed_mhd
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Collections
CollectionsCollections
Collections
Manav Prasad
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
Kenji HASUNUMA
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
boopathirajaraja1
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
Irfanhabeeb18
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
Best core & advanced java classes in mumbai
Best core & advanced java classes in mumbaiBest core & advanced java classes in mumbai
Best core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Constantine Nosovsky
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
hemanth248901
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
ssuseredfbe9
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - Collections
Mohammad Shaker
 
java collections
java collectionsjava collections
java collections
javeed_mhd
 

Similar to JAVA PROGRAMMING - The Collections Framework (20)

collections
collectionscollections
collections
 
07 java collection
07 java collection07 java collection
07 java collection
 
Practical cats
Practical catsPractical cats
Practical cats
 
Collections
CollectionsCollections
Collections
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collections
CollectionsCollections
Collections
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Best core & advanced java classes in mumbai
Best core & advanced java classes in mumbaiBest core & advanced java classes in mumbai
Best core & advanced java classes in mumbai
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - Collections
 
Collections
CollectionsCollections
Collections
 
java collections
java collectionsjava collections
java collections
 

More from Jyothishmathi Institute of Technology and Science Karimnagar

JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES XML
WEB TECHNOLOGIES XMLWEB TECHNOLOGIES XML
WEB TECHNOLOGIES- PHP Programming
WEB TECHNOLOGIES-  PHP ProgrammingWEB TECHNOLOGIES-  PHP Programming
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax AnalysisCOMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis: COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis:
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail SecurityCRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level SecurityCRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash FunctionsCRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key CiphersCRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWORK SECURITY
CRYPTOGRAPHY & NETWORK SECURITYCRYPTOGRAPHY & NETWORK SECURITY
Computer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS SystemsComputer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS Systems
Jyothishmathi Institute of Technology and Science Karimnagar
 

More from Jyothishmathi Institute of Technology and Science Karimnagar (20)

JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
WEB TECHNOLOGIES XML
WEB TECHNOLOGIES XMLWEB TECHNOLOGIES XML
WEB TECHNOLOGIES XML
 
WEB TECHNOLOGIES- PHP Programming
WEB TECHNOLOGIES-  PHP ProgrammingWEB TECHNOLOGIES-  PHP Programming
WEB TECHNOLOGIES- PHP Programming
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
 
COMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax AnalysisCOMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax Analysis
 
COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis: COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis:
 
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail SecurityCRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
 
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level SecurityCRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
 
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash FunctionsCRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
 
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key CiphersCRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
 
CRYPTOGRAPHY & NETWORK SECURITY
CRYPTOGRAPHY & NETWORK SECURITYCRYPTOGRAPHY & NETWORK SECURITY
CRYPTOGRAPHY & NETWORK SECURITY
 
Computer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS SystemsComputer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS Systems
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 

JAVA PROGRAMMING - The Collections Framework

  • 1. JAVA PROGRAMMING - The Collections Framework Dr R Jegadeesan Prof-CSE Jyothishmathi Institute of Technology and Science, Karimnagar
  • 2. SYLLABUS The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a Collection via an Iterator, Using an Iterator, The For-Each alternative, Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The Legacy Classes and Interfaces- Dictionary, Hashtable ,Properties, Stack, Vector More Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
  • 3. UNIT IV : COLLECTION FRAMEWORK Topic Name : Introduction to Collection Framework Topic : Introduction to Collection Framework Aim & Objective : To make the student understand the concept of Collection Interfaces and Collection Classes and Legacy Classes and Interfaces. Application With Example :Java Program Using Collection Interfaces and Collection Classes Limitations If Any : Reference Links : • Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pvt. Ltd. • https://www.javatpoint.com/collections-in-java • Video Link details • https://www.youtube.com/watch?v=v9zg9g_FbJY
  • 4. Universities & Important Questions : • What is the Collection framework in Java? • What are the main differences between array and collection? • Explain various interfaces used in Collection framework? • What is the difference between ArrayList and Vector? • What is the difference between ArrayList and LinkedList? • What is the difference between Iterator and ListIterator? • What is the difference between Iterator and Enumeration? • What is the difference between List and Set? • What does the hashCode() method? • What is the Dictionary class?
  • 5. ▪ Collection Overview ▪ Collection Classes ▪ Collection Interfaces ▪ Legacy Classes ▪ Legacy Interfaces UNIT – IV CONTENTS
  • 6. 6 Collection Overview • List<E> is a generic type (furthermore it’s a generic interface) • ArrayList<E> is a generic class, which implements List<E> public class ArrayList<E> implements List<E> { private E[] elementData; private int size; ... //stuff public boolean add(E o) { elementData[size++] = o; return true; } public E get(int i) { return elementData[i]; } //etc... } E is a type variable/ type parameter List<Money> list = new ArrayList<Money>(); List/ArrayList both parameterised with Money When you parameterise ArrayList<E> with Money, think of it as: E “becomes” Money public class ArrayList implements List<Money> { private Money[] elementData; private int size; ... //stuff public boolean add(Money o) { elementData[size++] = o; return true; } public Money get(int i) { return elementData[i]; } //etc... }
  • 7. 7 More than just Lists… • ArrayLists and LinkedLists are just two of the many classes comprising the Java Collections Framework (JCF) • A collection is an object that maintains references to others objects – Essentially a subset of data structures • JCF forms part of the java.util package and provides: – Interfaces • Each defines the operations and contracts for a particular type of collection (List, Set, Queue, etc) • Idea: when using a collection object, it’s sufficient to know its interface – Implementations • Reusable classes that implement above interfaces (e.g. LinkedList, HashSet) – Algorithms • Useful polymorphic methods for manipulating and creating objects whose classes implement collection interfaces • Sorting, index searching, reversing, replacing etc.
  • 8. 8 Interfaces Root interface for operations common to all types of collections Specialises collection with operations for FIFO and priority queues. Stores a sequence of elements, allowing indexing methods A special Collection that cannot contain duplicates. Special Set that retains ordering of elements. Stores mappings from keys to values Special map in which keys are ordered Generalisation Specialisation Collection Set List Queue SortedSet Map SortedMap
  • 10. 10 java.util.Iterator<E> • Think about typical usage scenarios for Collections – Retrieve the list of all patients – Search for the lowest priced item • More often than not you would have to traverse every element in the collection – be it a List, Set, or your own datastructure • Iterators provide a generic way to traverse through a collection regardless of its implementation a f g d b c e i h a b c d e f g h i a b c d e f g h i Iterator next():d iterator() iterator() Set List hasNext()?
  • 11. 11 Using an Iterator • Quintessential code snippet for collection iteration: public void list(Collection<Item> items) { Iterator<Item> it = items.iterator(); while(it.hasNext()) { Item item = it.next(); System.out.println(item.getTitle()); } } +hasNext():boolean +next():E +remove():void <<interface>> Iterator<E> Design notes: Above method takes in an object whose class implements Collection List, ArrayList, LinkedList, Set, HashSet, TreeSet, Queue, MyOwnCollection, etc We know any such object can return an Iterator through method iterator() We don’t know the exact implementation of Iterator we are getting, but we don’t care, as long as it provides the methods next() and hasNext() Good practice: Program to an interface!
  • 12. 12 java.lang.Iterable<T> • This is called a “for-each” statement – For each item in items • This is possible as long as items is of type Iterable – Defines single method iterator() • Collection (and hence all its subinterfaces) implements Iterable • You can do this to your own implementation of Iterable too! – To do this you may need to return your own implementation of Iterator Iterator<Item> it = items.iterator(); while(it.hasNext()) { Item item = it.next(); System.out.println(item); } for (Item item : items) { System.out.println(item); } = <<interface>> Iterable<T> +iterator():Iterator<T> Collection<T> MyBag<T> List<T> Set<T> etc
  • 13. 13 java.util.Collections • Offers many very useful utilities and algorithms for manipulating and creating collections – Sorting lists – Index searching – Finding min/max – Reversing elements of a list – Swapping elements of a list – Replacing elements in a list – Other nifty tricks • Saves you having to implement them yourself → reuse
  • 14. 14 Collections.sort() • Java’s implementation of merge sort – ascending order public static <T extends Comparable<? super T>> void sort(List<T> list) 1) public static <T> void sort(List<T> list, Comparator<? super T> c) 2) Translation: 1. Only accepts a List parameterised with type implementing Comparable 2. Accepts a List parameterised with any type as long as you also give it a Comparator implementation that defines the ordering for that type What types of objects can you sort? Anything that has an ordering Two sort() methods: sort a given List according to either 1) natural ordering of elements or an 2) externally defined ordering. e b c d 0 1 2 3 4 b f 5 6 a a b b c 0 1 2 3 4 d e 5 6 f      
  • 15. 15 java.lang.Comparable<T> • A generic interface with a single method: int compareTo(T) – Return 0 if this = other – Return any +’ve integer if this > other – Return any –’ve integer if this < other • Implement this interface to define natural ordering on objects of type T public class Money implements Comparable<Money> { ... public int compareTo( Money other ) { if( this.cents == other.cents ) { return 0; } else if( this.cents < other.cents ) { return -1; } else { return 1; } } A more concise way of doing this? (hint: 1 line) return this.cents – other.cents; m1 = new Money(100,0); m2 = new Money(50,0); m1.compareTo(m2) returns 1;
  • 16. 16 Natural-order sorting List<Money> funds = new ArrayList<Money>(); funds.add(new Money(100,0)); funds.add(new Money(5,50)); funds.add(new Money(-40,0)); funds.add(new Money(5,50)); funds.add(new Money(30,0)); Collections.sort(funds); System.out.println(funds); List<CD> albums = new ArrayList<CD>(); albums.add(new CD("Street Signs","Ozomatli",2.80)); //etc... Collections.sort(albums); public static <T extends Comparable<? super T>> void sort(List<T> list)  What’s the output? [-40.0, 5.50, 5.50, 30.0, 100.0] CD does not implement a Comparable interface Wildcard (later)
  • 17. 17 java.util.Comparator<T> • Useful if the type of elements to be sorted is not Comparable, or you want to define an alternative ordering • Also a generic interface that defines methods compare(T,T) and equals(Object) – Usually only need to define compare(T,T) • Define ordering by CD’s getPrice() → Money – Note: PriceComparator implements a Comparator para- meterised with CD → T “becomes” CD public class PriceComparator implements Comparator<CD> { public int compare(CD c1, CD c2) { return c1.getPrice().compareTo(c2.getPrice()); } } +compare(T o1, T o2):int +equals(Object other):boolean <<interface>> Comparator<T> CD +getTitle():String +getArtist():String +getPrice():Money Comparator and Comparable going hand in hand ☺
  • 18. 18 Comparator sorting • Note, in sort(), Comparator overrides natural ordering – i.e. Even if we define natural ordering for CD, the given comparator is still going to be used instead – (On the other hand, if you give null as Comparator, then natural ordering is used) List<CD> albums = new ArrayList<CD>(); albums.add(new CD("Street Signs","Ozomatli",new Money(3,50))); albums.add(new CD("Jazzinho","Jazzinho",new Money(2,80))); albums.add(new CD("Space Cowboy","Jamiroquai",new Money(5,00))); albums.add(new CD("Maiden Voyage","Herbie Hancock",new Money(4,00))); albums.add(new CD("Here's the Deal","Liquid Soul",new Money(1,00))); Collections.sort(albums, new PriceComparator()); System.out.println(albums); public static <T> void sort(List<T> list, Comparator<? super T> c) implements Comparator<CD>
  • 19. 19 Set<E> • Mathematical Set abstraction – contains no duplicate elements – i.e. no two elements e1 and e2 such that e1.equals(e2) +add(E):boolean +remove(Object):boolean +contains(Object):boolean +isEmpty():boolean +size():int +iterator():Iterator<E> etc… <<interface>> Set<E> remove(c) →true a b c d remove(x) →false add(x) →true a b c d x add(b) →false contains(e) →true ? contains(x) →false a b c d e isEmpty() →false size() →5 +first():E +last():E etc… <<interface>> SortedSet<E>
  • 20. 20 HashSet<E> • Typically used implementation of Set. • Hash? Implemented using HashMap (later) • Parameterise Sets just as you parameterise Lists • Efficient (constant time) insert, removal and contains check – all done through hashing • x and y are duplicates if x.equals(y) • How are elements ordered? Quiz: Set<String> words = new HashSet<String>(); words.add("Bats"); words.add("Ants"); words.add("Crabs"); words.add("Ants"); System.out.println(words.size()); for (String word : words) { System.out.println(word); } ? a) Bats, Ants, Crabs b) Ants, Bats, Crabs c) Crabs, Bats, Ants d) Nondeterministic +add(E):boolean +remove(Object):boolean +contains(Object):boolean +size():int +iterator():Iterator<E> etc… <<interface>> Set<E> HashSet<E> 3
  • 21. 21 TreeSet<E> (SortedSet<E>) • If you want an ordered set, use an implementation of a SortedSet: TreeSet • What’s up with “Tree”? Red-black tree • Guarantees that all elements are ordered (sorted) at all times – add() and remove() preserve this condition – iterator() always returns the elements in a specified order • Two ways of specifying ordering – Ensuring elements have natural ordering (Comparable) – Giving a Comparator<E> to the constructor • Caution: TreeSet considers x and y are duplicates if x.compareTo(y) == 0 (or compare(x,y) == 0) +first():E +last():E etc… <<interface>> SortedSet<E> TreeSet<E>
  • 22. 22 TreeSet construction • String has a natural ordering, so empty constructor Set<String> words = new TreeSet<String>(); words.add("Bats"); words.add("Ants"); words.add("Crabs"); for (String word : words) { System.out.println(word); } Set<CD> albums = new TreeSet<CD>(new PriceComparator()); albums.add(new CD("Street Signs","O",new Money(3,50))); albums.add(new CD("Jazzinho","J",new Money(2,80))); albums.add(new CD("Space Cowboy","J",new Money(5,00))); albums.add(new CD("Maiden Voyage","HH",new Money(4,00))); albums.add(new CD("Here’s the Deal","LS",new Money(2,80))); System.out.println(albums.size()); for (CD album : albums) { System.out.println(album); } But CD doesn’t, so you must pass in a Comparator to the constructor What’s the output? 4 Jazzinho; Street; Maiden; Space What’s the output? Ants; Bats; Crabs
  • 23. 23 Map<K,V> • Stores mappings from (unique) keys (type K) to values (type V) – See, you can have more than one type parameters! • Think of them as “arrays” but with objects (keys) as indexes – Or as “directories”: e.g. "Bob" → 021999887 +put(K,V):V +get(Object):V +remove(Object):V +size():int +keySet():Set<K> +values():Collection<V> etc… <<interface>> Map<K,V> +firstKey():K +lastKey():K etc… <<interface>> SortedMap<K,V> get(k) →a a b c b k m p n get(x) →null keys values put(x,e) →null a b c b k m p n e x put(k,f) →a a b c b k m p n f size() →4 remove(n) →b remove(x) →null a b c b k m p n keySet() →Set k m p n values() →Collection a b c b
  • 24. 24 HashMap<K,V> • aka Hashtable (SE250) • keys are hashed using Object.hashCode() – i.e. no guaranteed ordering of keys • keySet() returns a HashSet • values() returns an unknown Collection +put(K,V):V +get(Object):V +remove(Object):V +size():int +keySet():Set<K> +values():Collection<V> etc… <<interface>> Map<K,V> HashMap<K,V> Map<String, Integer> directory = new HashMap<String, Integer>(); directory.put("Mum", new Integer(9998888)); directory.put("Dad", 9998888); directory.put("Bob", 12345678); directory.put("Edward", 5553535); directory.put("Bob", 1000000); System.out.println(directory.size()); for (String key : directory.keySet()) { System.out.print(key+"'s number: "); System.out.println(directory.get(key)); } System.out.println(directory.values()); 4 or 5? Set<String> “autoboxing” What’s Bob’s number?
  • 25. 25 TreeMap<K,V> • Guaranteed ordering of keys (like TreeSet) – In fact, TreeSet is implemented using TreeMap ☺ – Hence keySet() returns a TreeSet • values() returns an unknown Collection – ordering depends on ordering of keys +firstKey():K +lastKey():K etc… <<interface>> SortedMap<K,V> TreeMap<K,V> Map<String, Integer> directory = new TreeMap<String, Integer>(); directory.put("Mum", new Integer(9998888)); directory.put("Dad", 9998888); directory.put("Bob", 12345678); directory.put("Edward", 5553535); directory.put("Bob", 1000000); System.out.println(directory.size()); for (String key : directory.keySet()) { System.out.print(key+"'s #: "); System.out.println(directory.get(key)); } System.out.println(directory.values()); Loop output? Bob's #: 1000000 Dad's #: 9998888 Edward's #: 5553535 Mum's #: 9998888 4 ? Empty constructor → natural ordering
  • 26. 26 TreeMap with Comparator • As with TreeSet, another way of constructing TreeMap is to give a Comparator → necessary for non-Comparable keys Map<CD, Double> ratings = new TreeMap<CD, Double>(new PriceComparator()); ratings.put(new CD("Street Signs","O",new Money(3,50)), 8.5); ratings.put(new CD("Jazzinho","J",new Money(2,80)), 8.0); ratings.put(new CD("Space Cowboy","J",new Money(5,00)), 9.0); ratings.put(new CD("Maiden Voyage","H",new Money(4,00)), 9.5); ratings.put(new CD("Here's the Deal","LS",new Money(2,80)), 9.0); System.out.println(ratings.size()); for (CD key : ratings.keySet()) { System.out.print("Rating for "+key+": "); System.out.println(ratings.get(key)); } System.out.println("Ratings: "+ratings.values()); 4 Depends on key ordering Ordered by key’s price