SlideShare a Scribd company logo
ALLPPT.com _ Free PowerPoint Templates, Diagrams and Charts
By
Anup Kumar Sahoo
Date- 05.01.2015
Collection Framework
 Collection Framework
 Design scenarios to illustrate usage of collection classes and interfaces
List – Sort, Binary Search and other utility methods
 Arrays - Sort, Binary Search and other utility methods
 Comparator and Comparable interfaces
 Effect of natural ordering of primitive and String classes on sorting.
 When to use which Data Structure
 Best Practices
 Questions : Choose a collection based on a stated requirement
 Questions : SCJP
Agenda
Collections Framework
A framework is an extensive set of interfaces, abstract classes and
concrete classes together with support tools
Framework is provided in java.util package and comprises three
parts:
1. Core interfaces
2. Set of implementations.
3. Utility methods
Collection Interfaces
Collections are primarily defined through a set of
interfaces
 Supported by a set of classes that implement the
interfaces
 Does not hold primitives, use wrapper classes
 Collections can be type safe, i.e. type of elements
can be specified using Generics
Example - Type Safe:
Collection<String> stringCollection = new LinkedList<String>();
stringCollection.add(“GoodMorning’); - Right
stringCollection.add(8); - Wrong
Collection<Integer> integerCollection = new LinkedList<Integer>();
integerCollection.add(10);
integerCollection.add(new Integer(12));
integerCollection.add(“hello”); - Wrong
Hierarchy
General Purpose Implementations
Implementing Map Interface
Primary Classifications
Collections can be primarily grouped into four types
 List – Lists of things
 Sets – Unique things
 Maps – Things with a unique ID
 Queues – Things arranged by the order in which
they are to be processed
Above can be further classified into
 Sorted
 Unsorted
 Ordered
 Unordered
Primary Classifications
An implementation class can be
- unsorted and unordered
- ordered but unsorted
- ordered and sorted
- but implementation class can never be sorted and
unordered.
 Ordered collection ?
 Sorted collection ?
List Interface
Also called as sequence, is an ordered collection that can contain
duplicate elements
List indices are zero based
One thing that list has and non-lists don’t have is a set of
methods related to index.
 get(int index), indexOf(Object o), add(int index, Object obj)
List Example
Iterator Interface
Set Interface
Allows only unique elements
equals() methods determines whether two methods are identical
HashSet
- Uses hashcode of the inserted object, implemented using a hash table
- No ordering of elements
- add, remove and contains methods have constant time complexity
LinkedHashSet
- Ordered version of HashSet that maintains doubly linked list
- Useful in making set copies, such that original set’s iteration ordering is
preserved
TreeSet
- Sorted collection. Implemented using tree structure and guarantees ordering of
elements (natural order - ascending)
- add, remove and contains methods have logarithmic time complexity
Note: While using HashSet or LinkedHashSet, the objects added to them must override
hashCode().
Set Interface Ex.
Map Interface
Maps are similar to collections but are actually represented by an
entirely different class hierarchy
Map is an object that maps keys to values
Also called as Associative array or a dictionary
Depends on equals() method to determine whether two keys are same
or different . Keys cannot be duplicated.
Methods to retrieve key, values and key–value pair
- keySet() : returns a Set
- values() : returns a Collection
- entrySet() : returns a Set
Map Implementation
HashMap
- The implementation is based on a hash table.
- No ordering on (key, value) pairs – unsorted and unordered
- Allows one null key and multiple null values
 Hashtable
- Methods are synchronized
- Key or value cannot be null
 LinkedHashMap
- Maintains insertion order.
- Provides fast iteration but slower in adding and removing
operation
TreeMap
- Sorted map. Sorted by natural order and also allows to define
custom sort order.
- Implementation based on tree structure. (key – value) pairs
are ordered on the key.
Map Example
Map<String,String> map = new HashMap<String,String>();
map.put(“rama", "03-9516743");
map.put(“Sita", "09-5076452");
map.put("Leo", "08-5530098");
map.put("Rita", "06-8201124");
System.out.println(map);
//Iterating over key
for (String key : map.keySet()) {System.out.println(key);}
//Iterating over key-value pair
for (Map.Entry<String,String> entry: map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output: {Leo=08-5530098, rama=03-9516743, Sita=06-8201124}
Queue Interface
Queues support all of the standard Collection methods
Queue Implementation :
Priority Queue:
- purpose is to create a “priority-in, priority out” queue as
opposed to FIFO queue.
- Elements are either ordered naturally or according to
Comparator
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(3);
queue.add(1);
queue.add(new Integer(1));
queue.add(new Integer(6));
queue.remove();
System.out.println(queue);
Understand
 equals()
Collections Algorithm
 Defined in Collections class
 Main Algorithms
- sort
- binarySearch
- reverse
- shuffle
- min
- max
use of word Collection
 collection (lowercase c), which represents any of the data structures
in which objects are stored and iterated over.
 Collection (capital C), which is actually the java.util.Collection
interface from which Set, List, and Queue extend. (That's right,
extend, not implement. There are no direct implementations of
Collection.)
 Collections (capital C and ends with s) is the java.util.Collections
class that holds a pile of static utility methods for use with
collections.
ArrayList and Arrays
 Manipulate by Sorting
 Performing a binary search
 Converting the list to array and array to list
 Use java.util.Comparator and java.lang.Comparable to affect
sorting
ArrayList
Advantages over Array
- It can grow dynamically
- provides more powerful insertion and search mechanisms
than arrays
Ex:import java.util.*;
public class TestArrayList {
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
String s = "hi";
test.add("string");
test.add(s);
test.add(s+s);
System.out.println(test.size());
System.out.println(test.contains(42));
System.out.println(test.contains("hihi"));
test.remove("hi");
System.out.println(test.size());
} }
Output : 3 false true 2
Sorting Collections
import java.util.*;
class TestSort1 {
public static void main(String[] args) {
ArrayList<String> stuff = new ArrayList<String>();
stuff.add("Denver");
stuff.add("Boulder");
stuff.add("Vail");
stuff.add("Aspen");
stuff.add("Telluride");
System.out.println("unsorted " + stuff);
Collections.sort(stuff);
System.out.println("sorted " + stuff);
}
}
Output:
unsorted [Denver, Boulder, Vail, Aspen, Telluride]
sorted [Aspen, Boulder, Denver, Telluride, Vail]
Comparable interface
Illustrate an example – MusicList
Used by Collections.sort() method and Arrays.sort() to sort lists
and arrays respectively.
Only one sort sequence can be created
compareTo() method should be implemented
int x = thisObject.compareTo(anotherObject); returns negative, positive or zero
value
Ex:
Class MusicInfo implements Comparable< MusicInfo > {
String title;
// existing code
public int compareTo(MusicInfo d) {
return title.compareTo(d.getTitle());
} }
Comparator Interface
 The Comparator interface provides the capability to sort a given
collection any number of different ways.
 Can be used to sort instances of any class
 Easy to implement and has a method compare()
 Example
import java.util.*;
class GenreSort implements Comparator<DVDInfo> {
public int compare(DVDInfo one, DVDInfo two) {
return one.getGenre().compareTo(two.getGenre());
}
}
Comparator vs Comparable
Comparable Comparator
int objOne.compareTo(objTwo) int compare(objOne, objTwo)
Returns
negative if objOne < objTwo
zero if objOne == objTwo
positive if objOne > objTwo
Same as Comparable
You must modify the class whose
instances you want to sort.
You build a class separate from the
class whose instances you
want to sort.
Only one sort sequence can be created
Implemented by String, Wrapper classes, Date, etc
Many sort sequences can be
created
Implemented by third party classes
Sorting Arrays
 Arrays.sort(arrayToSort)
 Arrays.sort(arrayToSort, Comparator)
 sort() method has been overloaded many times to provide sort
methods for every type of primitive.
 Primitives are always sorted based on natural order
Note : Elements to be sorted must be mutually comparable
Searching Arrays and Collections
Certain rules apply while searching
1. Searches are performed using the binarySearch() method.
2. Successful searches return the int index of the element being
searched.
3. Unsuccessful searches return an int index that represents the
insertion point.
4. The collection/array being searched must be sorted before you
can search it.
5. If you attempt to search an array or collection that has not
already been sorted, the results of the search will not be
predictable.
6. If the collection/array you want to search was sorted in
natural order, it must be searched in natural order.
7. If the collection/array you want to search was sorted using a
Comparator, it must be searched using the same Comparator, which is
passed as the second argument to the binarySearch() method. Remember
that Comparators cannot be used when searching arrays of primitives.
Example for Binary Search
import java.util.*;
class SearchObjArray {
– public static void main(String [] args) {
– String [] sa = {"one", "two", "three", "four"};
– Arrays.sort(sa); // #1
– for(String s : sa)
– System.out.print(s + " ");
– System.out.println("none = "
– + Arrays.binarySearch(sa,"one")); // #2
– System.out.println("now reverse sort");
– ReSortComparator rs = new ReSortComparator(); // #3
– Arrays.sort(sa,rs);
– for(String s : sa)
– System.out.print(s + " ");
– System.out.println("none = "
– + Arrays.binarySearch(sa,"one")); // #4
– System.out.println("one = "
– + Arrays.binarySearch(sa,"one",rs)); // #5
– }
– static class ReSortComparator
– implements Comparator<String> { // #6
– public int compare(String a, String b) {
– return b.compareTo(a); // #7
– }
– }
– }
four one three two -> array
sorted alphabetically
one = 1 ->
search for element location 1
now reverse sort
two three one four -> reverse
sort
one = -1
one = 2 ->
search passing the comparator
Result
Converting Arrays – Lists -Arrays
 The List and Set classes have toArray() methods
 The Arrays class has a method called asList()
Ex:
String[] sa = {"one", "two", "three", "four"};
List sList = Arrays.asList(sa); // make a List
System.out.println("size " + sList.size());
System.out.println("idx2 " + sList.get(2));
sList.set(3,"six"); // change List
sa[1] = "five"; // change array
for(String s : sa)
System.out.print(s + " ");
System.out.println("nsl[1] " + sList.get(1));
This produces :
– size 4
– idx2 three
– one five three six
– sl[1] five
Example : List to Array
List<Integer> iL = new ArrayList<Integer>();
for(int x=0; x<3; x++)
iL.add(x);
Object[] oa = iL.toArray(); // create an Object array
Integer[] ia2 = new Integer[3];
ia2 = iL.toArray(ia2); // create an Integer array
Natural ordering
spaces sort before characters and that uppercase letters sort
before lowercase characters
String[] sa = {">ff<", "> f<", ">f <", ">FF<" }; // ordered?
PriorityQueue<String> pq3 = new PriorityQueue<String>();
for(String s : sa)
pq3.offer(s);
for(String s : sa)
System.out.print(pq3.poll() + " ");
This produces:
> f< >FF< >f < >ff<
Java Collections Framework
Learning's
Specify an implementation only when a collection is constructed
- public void mySet(HashSet s){…} -> Works
- public void mySet(Set s) {…} -> Better
- s.add() invokes HashSet.add() -> Polymorphism
 ArrayLists behave like Vectors without synchronization and therefore execute
faster than Vectors because ArrayLists do not have the overhead of thread
synchronization.
ArrayList implements the RandomAccess interface, and LinkedList. does not. Note
that Collections.binarySearch does take advantage of the RandomAccess property, to
optimize searches
LinkedLists can be used to create stacks, queues, trees and deques (double-ended
queues, pronounced “decks”). The collections framework provides implementations of
some of these data structures.
Appending elements to the end of a list has a fixed averaged cost for both
ArrayList and LinkedList. For ArrayList, appending typically involves setting an
internal array location to the element reference, but occasionally results in the
array being reallocated. For LinkedList, the cost is uniform and involves allocating
an internal Entry object.
Learning's
 Inserting or deleting elements in the middle of an ArrayList implies that the
rest of the list must be moved. Inserting or deleting elements in the middle of
a LinkedList has fixed cost.
 A LinkedList does not support efficient random access
An ArrayList has space overhead in the form of reserve capacity at the end of
the list. A LinkedList has significant space overhead per element
Use a Tree only if you need them sorted, otherwise use a Hash
Sometimes a Map structure is a better choice than a List.
There is one exception to the rule that LinkedHashSets are slower than
HashSets: iteration over a LinkedHashSet is generally faster than iteration over
a HashSet
LinkedHashSet and TreeSet cost more than HashSet, but do more. A LinkedHashSet
is useful in making set copies, such that the original set's iteration ordering
is preserved:
void f(Set s) { Set copy = new LinkedHashSet(s);}
Java Collections Framework

More Related Content

What's hot (20)

PDF
Collections In Java
Binoj T E
 
PPT
Java collection
Arati Gadgil
 
PDF
5 collection framework
Minal Maniar
 
PDF
Java Collection framework
ankitgarg_er
 
ODP
Java Collections
parag
 
PDF
Collections Api - Java
Drishti Bhalla
 
PPTX
Java 8 presentation
Van Huong
 
PPTX
Collections framework in java
yugandhar vadlamudi
 
PDF
07 java collection
Abhishek Khune
 
PPTX
Java - Collections framework
Riccardo Cardin
 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPSX
Collections - Lists, Sets
Hitesh-Java
 
PPTX
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
Arrays in Java
Naz Abdalla
 
PPT
Jsp ppt
Vikas Jagtap
 
PDF
Java 8 features
NexThoughts Technologies
 
PDF
Generics
Ravi_Kant_Sahu
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
Collections In Java
Binoj T E
 
Java collection
Arati Gadgil
 
5 collection framework
Minal Maniar
 
Java Collection framework
ankitgarg_er
 
Java Collections
parag
 
Collections Api - Java
Drishti Bhalla
 
Java 8 presentation
Van Huong
 
Collections framework in java
yugandhar vadlamudi
 
07 java collection
Abhishek Khune
 
Java - Collections framework
Riccardo Cardin
 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Collections in Java Notes
Shalabh Chaudhary
 
Collections - Lists, Sets
Hitesh-Java
 
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Java 8 Lambda Expressions
Scott Leberknight
 
Arrays in Java
Naz Abdalla
 
Jsp ppt
Vikas Jagtap
 
Java 8 features
NexThoughts Technologies
 
Generics
Ravi_Kant_Sahu
 
Classes, objects in JAVA
Abhilash Nair
 

Viewers also liked (12)

PDF
Java Collections API
Alex Miller
 
PDF
Java 8 new features
Framgia Vietnam
 
PPSX
Java annotations
FAROOK Samath
 
PPTX
Java Annotations
Serhii Kartashov
 
PPT
java collections
javeed_mhd
 
PPTX
Java collections
Amar Kutwal
 
PPTX
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
PDF
Java Collections Tutorials
Prof. Erwin Globio
 
PDF
Node.js and Selenium Webdriver, a journey from the Java side
Mek Srunyu Stittri
 
PDF
Annotation Processing in Android
emanuelez
 
PDF
Java Annotation Processing: A Beginner Walkthrough
Mahfuz Islam Bhuiyan
 
PPTX
Annotations in Java
Kirill Kulakov
 
Java Collections API
Alex Miller
 
Java 8 new features
Framgia Vietnam
 
Java annotations
FAROOK Samath
 
Java Annotations
Serhii Kartashov
 
java collections
javeed_mhd
 
Java collections
Amar Kutwal
 
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
Java Collections Tutorials
Prof. Erwin Globio
 
Node.js and Selenium Webdriver, a journey from the Java side
Mek Srunyu Stittri
 
Annotation Processing in Android
emanuelez
 
Java Annotation Processing: A Beginner Walkthrough
Mahfuz Islam Bhuiyan
 
Annotations in Java
Kirill Kulakov
 
Ad

Similar to Java Collections Framework (20)

PPTX
22CS305-UNIT-1.pptx ADVANCE JAVA PROGRAMMING
logesswarisrinivasan
 
PPT
Collections
Rajkattamuri
 
PPT
Collections
Manav Prasad
 
PPT
Collections in Java
Khasim Cise
 
PPT
collections
javeed_mhd
 
PPTX
Updated_Java_Collections_Framework_Presentation.pptx
abhishekhatwal18
 
PPT
12_-_Collections_Framework
Krishna Sujeer
 
PPTX
Collections Training
Ramindu Deshapriya
 
PPTX
LJ_JAVA_FS_Collection.pptx
Raneez2
 
PPT
description of Collections, seaching & Sorting
mdimberu
 
DOCX
Java collections notes
Surendar Meesala
 
PPTX
Advanced Java - UNIT 3.pptx
eyemitra1
 
PDF
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
DOCX
ArrayList.docx
veerendranath12
 
PPTX
Collections
Marwa Dosoky
 
PPTX
oop lecture framework,list,maps,collection
ssuseredfbe9
 
PPTX
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
PPTX
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
PPTX
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
PPTX
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
22CS305-UNIT-1.pptx ADVANCE JAVA PROGRAMMING
logesswarisrinivasan
 
Collections
Rajkattamuri
 
Collections
Manav Prasad
 
Collections in Java
Khasim Cise
 
collections
javeed_mhd
 
Updated_Java_Collections_Framework_Presentation.pptx
abhishekhatwal18
 
12_-_Collections_Framework
Krishna Sujeer
 
Collections Training
Ramindu Deshapriya
 
LJ_JAVA_FS_Collection.pptx
Raneez2
 
description of Collections, seaching & Sorting
mdimberu
 
Java collections notes
Surendar Meesala
 
Advanced Java - UNIT 3.pptx
eyemitra1
 
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
ArrayList.docx
veerendranath12
 
Collections
Marwa Dosoky
 
oop lecture framework,list,maps,collection
ssuseredfbe9
 
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
Ad

Recently uploaded (20)

PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 

Java Collections Framework

  • 1. ALLPPT.com _ Free PowerPoint Templates, Diagrams and Charts By Anup Kumar Sahoo Date- 05.01.2015 Collection Framework
  • 2.  Collection Framework  Design scenarios to illustrate usage of collection classes and interfaces List – Sort, Binary Search and other utility methods  Arrays - Sort, Binary Search and other utility methods  Comparator and Comparable interfaces  Effect of natural ordering of primitive and String classes on sorting.  When to use which Data Structure  Best Practices  Questions : Choose a collection based on a stated requirement  Questions : SCJP Agenda
  • 3. Collections Framework A framework is an extensive set of interfaces, abstract classes and concrete classes together with support tools Framework is provided in java.util package and comprises three parts: 1. Core interfaces 2. Set of implementations. 3. Utility methods
  • 4. Collection Interfaces Collections are primarily defined through a set of interfaces  Supported by a set of classes that implement the interfaces  Does not hold primitives, use wrapper classes  Collections can be type safe, i.e. type of elements can be specified using Generics Example - Type Safe: Collection<String> stringCollection = new LinkedList<String>(); stringCollection.add(“GoodMorning’); - Right stringCollection.add(8); - Wrong Collection<Integer> integerCollection = new LinkedList<Integer>(); integerCollection.add(10); integerCollection.add(new Integer(12)); integerCollection.add(“hello”); - Wrong
  • 8. Primary Classifications Collections can be primarily grouped into four types  List – Lists of things  Sets – Unique things  Maps – Things with a unique ID  Queues – Things arranged by the order in which they are to be processed Above can be further classified into  Sorted  Unsorted  Ordered  Unordered
  • 9. Primary Classifications An implementation class can be - unsorted and unordered - ordered but unsorted - ordered and sorted - but implementation class can never be sorted and unordered.  Ordered collection ?  Sorted collection ?
  • 10. List Interface Also called as sequence, is an ordered collection that can contain duplicate elements List indices are zero based One thing that list has and non-lists don’t have is a set of methods related to index.  get(int index), indexOf(Object o), add(int index, Object obj)
  • 13. Set Interface Allows only unique elements equals() methods determines whether two methods are identical HashSet - Uses hashcode of the inserted object, implemented using a hash table - No ordering of elements - add, remove and contains methods have constant time complexity LinkedHashSet - Ordered version of HashSet that maintains doubly linked list - Useful in making set copies, such that original set’s iteration ordering is preserved TreeSet - Sorted collection. Implemented using tree structure and guarantees ordering of elements (natural order - ascending) - add, remove and contains methods have logarithmic time complexity Note: While using HashSet or LinkedHashSet, the objects added to them must override hashCode().
  • 15. Map Interface Maps are similar to collections but are actually represented by an entirely different class hierarchy Map is an object that maps keys to values Also called as Associative array or a dictionary Depends on equals() method to determine whether two keys are same or different . Keys cannot be duplicated. Methods to retrieve key, values and key–value pair - keySet() : returns a Set - values() : returns a Collection - entrySet() : returns a Set
  • 16. Map Implementation HashMap - The implementation is based on a hash table. - No ordering on (key, value) pairs – unsorted and unordered - Allows one null key and multiple null values  Hashtable - Methods are synchronized - Key or value cannot be null  LinkedHashMap - Maintains insertion order. - Provides fast iteration but slower in adding and removing operation TreeMap - Sorted map. Sorted by natural order and also allows to define custom sort order. - Implementation based on tree structure. (key – value) pairs are ordered on the key.
  • 17. Map Example Map<String,String> map = new HashMap<String,String>(); map.put(“rama", "03-9516743"); map.put(“Sita", "09-5076452"); map.put("Leo", "08-5530098"); map.put("Rita", "06-8201124"); System.out.println(map); //Iterating over key for (String key : map.keySet()) {System.out.println(key);} //Iterating over key-value pair for (Map.Entry<String,String> entry: map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } Output: {Leo=08-5530098, rama=03-9516743, Sita=06-8201124}
  • 18. Queue Interface Queues support all of the standard Collection methods Queue Implementation : Priority Queue: - purpose is to create a “priority-in, priority out” queue as opposed to FIFO queue. - Elements are either ordered naturally or according to Comparator Queue<Integer> queue = new LinkedList<Integer>(); queue.add(3); queue.add(1); queue.add(new Integer(1)); queue.add(new Integer(6)); queue.remove(); System.out.println(queue); Understand  equals()
  • 19. Collections Algorithm  Defined in Collections class  Main Algorithms - sort - binarySearch - reverse - shuffle - min - max
  • 20. use of word Collection  collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.  Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement. There are no direct implementations of Collection.)  Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.
  • 21. ArrayList and Arrays  Manipulate by Sorting  Performing a binary search  Converting the list to array and array to list  Use java.util.Comparator and java.lang.Comparable to affect sorting
  • 22. ArrayList Advantages over Array - It can grow dynamically - provides more powerful insertion and search mechanisms than arrays Ex:import java.util.*; public class TestArrayList { public static void main(String[] args) { List<String> test = new ArrayList<String>(); String s = "hi"; test.add("string"); test.add(s); test.add(s+s); System.out.println(test.size()); System.out.println(test.contains(42)); System.out.println(test.contains("hihi")); test.remove("hi"); System.out.println(test.size()); } } Output : 3 false true 2
  • 23. Sorting Collections import java.util.*; class TestSort1 { public static void main(String[] args) { ArrayList<String> stuff = new ArrayList<String>(); stuff.add("Denver"); stuff.add("Boulder"); stuff.add("Vail"); stuff.add("Aspen"); stuff.add("Telluride"); System.out.println("unsorted " + stuff); Collections.sort(stuff); System.out.println("sorted " + stuff); } } Output: unsorted [Denver, Boulder, Vail, Aspen, Telluride] sorted [Aspen, Boulder, Denver, Telluride, Vail]
  • 24. Comparable interface Illustrate an example – MusicList Used by Collections.sort() method and Arrays.sort() to sort lists and arrays respectively. Only one sort sequence can be created compareTo() method should be implemented int x = thisObject.compareTo(anotherObject); returns negative, positive or zero value Ex: Class MusicInfo implements Comparable< MusicInfo > { String title; // existing code public int compareTo(MusicInfo d) { return title.compareTo(d.getTitle()); } }
  • 25. Comparator Interface  The Comparator interface provides the capability to sort a given collection any number of different ways.  Can be used to sort instances of any class  Easy to implement and has a method compare()  Example import java.util.*; class GenreSort implements Comparator<DVDInfo> { public int compare(DVDInfo one, DVDInfo two) { return one.getGenre().compareTo(two.getGenre()); } }
  • 26. Comparator vs Comparable Comparable Comparator int objOne.compareTo(objTwo) int compare(objOne, objTwo) Returns negative if objOne < objTwo zero if objOne == objTwo positive if objOne > objTwo Same as Comparable You must modify the class whose instances you want to sort. You build a class separate from the class whose instances you want to sort. Only one sort sequence can be created Implemented by String, Wrapper classes, Date, etc Many sort sequences can be created Implemented by third party classes
  • 27. Sorting Arrays  Arrays.sort(arrayToSort)  Arrays.sort(arrayToSort, Comparator)  sort() method has been overloaded many times to provide sort methods for every type of primitive.  Primitives are always sorted based on natural order Note : Elements to be sorted must be mutually comparable
  • 28. Searching Arrays and Collections Certain rules apply while searching 1. Searches are performed using the binarySearch() method. 2. Successful searches return the int index of the element being searched. 3. Unsuccessful searches return an int index that represents the insertion point. 4. The collection/array being searched must be sorted before you can search it. 5. If you attempt to search an array or collection that has not already been sorted, the results of the search will not be predictable. 6. If the collection/array you want to search was sorted in natural order, it must be searched in natural order. 7. If the collection/array you want to search was sorted using a Comparator, it must be searched using the same Comparator, which is passed as the second argument to the binarySearch() method. Remember that Comparators cannot be used when searching arrays of primitives.
  • 29. Example for Binary Search import java.util.*; class SearchObjArray { – public static void main(String [] args) { – String [] sa = {"one", "two", "three", "four"}; – Arrays.sort(sa); // #1 – for(String s : sa) – System.out.print(s + " "); – System.out.println("none = " – + Arrays.binarySearch(sa,"one")); // #2 – System.out.println("now reverse sort"); – ReSortComparator rs = new ReSortComparator(); // #3 – Arrays.sort(sa,rs); – for(String s : sa) – System.out.print(s + " "); – System.out.println("none = " – + Arrays.binarySearch(sa,"one")); // #4 – System.out.println("one = " – + Arrays.binarySearch(sa,"one",rs)); // #5 – } – static class ReSortComparator – implements Comparator<String> { // #6 – public int compare(String a, String b) { – return b.compareTo(a); // #7 – } – } – } four one three two -> array sorted alphabetically one = 1 -> search for element location 1 now reverse sort two three one four -> reverse sort one = -1 one = 2 -> search passing the comparator Result
  • 30. Converting Arrays – Lists -Arrays  The List and Set classes have toArray() methods  The Arrays class has a method called asList() Ex: String[] sa = {"one", "two", "three", "four"}; List sList = Arrays.asList(sa); // make a List System.out.println("size " + sList.size()); System.out.println("idx2 " + sList.get(2)); sList.set(3,"six"); // change List sa[1] = "five"; // change array for(String s : sa) System.out.print(s + " "); System.out.println("nsl[1] " + sList.get(1)); This produces : – size 4 – idx2 three – one five three six – sl[1] five
  • 31. Example : List to Array List<Integer> iL = new ArrayList<Integer>(); for(int x=0; x<3; x++) iL.add(x); Object[] oa = iL.toArray(); // create an Object array Integer[] ia2 = new Integer[3]; ia2 = iL.toArray(ia2); // create an Integer array
  • 32. Natural ordering spaces sort before characters and that uppercase letters sort before lowercase characters String[] sa = {">ff<", "> f<", ">f <", ">FF<" }; // ordered? PriorityQueue<String> pq3 = new PriorityQueue<String>(); for(String s : sa) pq3.offer(s); for(String s : sa) System.out.print(pq3.poll() + " "); This produces: > f< >FF< >f < >ff<
  • 34. Learning's Specify an implementation only when a collection is constructed - public void mySet(HashSet s){…} -> Works - public void mySet(Set s) {…} -> Better - s.add() invokes HashSet.add() -> Polymorphism  ArrayLists behave like Vectors without synchronization and therefore execute faster than Vectors because ArrayLists do not have the overhead of thread synchronization. ArrayList implements the RandomAccess interface, and LinkedList. does not. Note that Collections.binarySearch does take advantage of the RandomAccess property, to optimize searches LinkedLists can be used to create stacks, queues, trees and deques (double-ended queues, pronounced “decks”). The collections framework provides implementations of some of these data structures. Appending elements to the end of a list has a fixed averaged cost for both ArrayList and LinkedList. For ArrayList, appending typically involves setting an internal array location to the element reference, but occasionally results in the array being reallocated. For LinkedList, the cost is uniform and involves allocating an internal Entry object.
  • 35. Learning's  Inserting or deleting elements in the middle of an ArrayList implies that the rest of the list must be moved. Inserting or deleting elements in the middle of a LinkedList has fixed cost.  A LinkedList does not support efficient random access An ArrayList has space overhead in the form of reserve capacity at the end of the list. A LinkedList has significant space overhead per element Use a Tree only if you need them sorted, otherwise use a Hash Sometimes a Map structure is a better choice than a List. There is one exception to the rule that LinkedHashSets are slower than HashSets: iteration over a LinkedHashSet is generally faster than iteration over a HashSet LinkedHashSet and TreeSet cost more than HashSet, but do more. A LinkedHashSet is useful in making set copies, such that the original set's iteration ordering is preserved: void f(Set s) { Set copy = new LinkedHashSet(s);}