Java/J2EE Programming Training
Collections – Lists, Sets
Page 2Classification: Restricted
Agenda
• List – ArrayList, LinkedList
• Set – HashSet, LinkedHashSet, TreeSet
Collections Framework Diagram
Classification: Restricted Page 4
Collection Interface
Classification: Restricted Page 5
• Defines fundamental methods
•int size();
•boolean isEmpty();
•boolean contains(Object element);
•boolean add(Object element); // Optional
•boolean remove(Object element); // Optional
•Iterator iterator();
• These methods are enough to define the basic behavior of a collection
• Provides an Iterator to step through the elements in the Collection
Iterator Interface
• Defines three fundamental methods
•Object next()
•boolean hasNext()
•void remove()
• These three methods provide access to the contents of the
collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the collection
• Then you can use it or removeit
Classification: Restricted Page 6
Example - SimpleCollection
Classification: Restricted Page 7
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName()); for (int i=1; i
<= 10; i++) {
c.add(i + " * " + i + " ="+i*i);
}
Iterator iter = c.iterator(); while
(iter.hasNext())
System.out.println(iter.next());
}
}
List Interface Context
Classification: Restricted Page 8
Collection
List
ListIterator Interface
Classification: Restricted Page 9
• Extends the Iterator interface
• Defines three fundamental methods
• void add(Object o) - before current position
• boolean hasPrevious()
• Object previous()
• The addition of these three methods defines the basic behavior of
an ordered list
• A ListIterator knows position within list
ArrayList and LinkedList Context
ArrayList LinkedList
Classification: Restricted Page 10
Collection
List
List as part of Collection
Classification: Restricted Page 11
List Implementations
Classification: Restricted Page 12
• ArrayList
• low cost random access
• high cost insert and delete
• array that resizes if need be
• LinkedList
• sequential access
• low cost insert and delete
• high cost random access
• Vector
• Similar to ArrayList, but thread-safe
ArrayList overview
Classification: Restricted Page 13
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new
IllegalArgumentException(
"Illegal Capacity:
"+initialCapacity);
this.elementData = new Object[initialCapacity];
}
ArrayList methods
Classification: Restricted Page 14
• The indexed get and set methods of the List interface are
appropriate to use since ArrayLists are backed by an array
•Object get(int index)
•Object set(int index, Object element)
• Indexed add and remove are provided, but can be costly if used
frequently
•void add(int index, Object element)
•Object remove(int index)
• May want to resize in one shot if adding manyelements
•void ensureCapacity(int minCapacity)
LinkedList overview
Classification: Restricted Page 15
• Stores each element in a node
• Each node stores a link to the next and previousnodes
• Insertion and removal are inexpensive
• just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
• Start from beginning or end and traverse each node while
counting
LinkedList entries
Classification: Restricted Page 16
private static class Entry { Object
element;
Entry next; Entry
previous;
Entry(Object element, Entry next, Entry previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
private Entry header = new Entry(null, null, null); public
LinkedList() {
header.next = header.previous = header;
}
LinkedList methods
Classification: Restricted Page 17
• The list is sequential, so access it that way
•ListIterator listIterator()
• ListIterator knows about position
• use add() from ListIterator to add at a position
• use remove() from ListIterator to remove at a position
• LinkedList knows a few things too
•void addFirst(Object o), void addLast(Object o)
•Object getFirst(), Object getLast()
•Object removeFirst(), Object removeLast()
ArrayList vs. LinkedList vs. Vector
Classification: Restricted Page 18
From the hierarchy diagram, they all implement List interface. They are very
similar to use. Their main difference is their implementation which causes
different performance for different operations. ArrayList is implemented as a
resizable array. As more elements are added to ArrayList, its size is increased
dynamically. It's elements can be accessed directly by using the get and set
methods, since ArrayList is essentially an array. LinkedList is implemented as
a double linked list. Its performance on add and remove is better than
Arraylist, but worse on get and set methods. Vector is similar with ArrayList,
but it is synchronized. ArrayList is a better choice if your program is thread-
safe. Vector and ArrayList require space as more elements are added. Vector
each time doubles its array size, while ArrayList grow 50% of its size each
time. LinkedList, however, also implements Queue interface which adds more
methods than ArrayList and Vector, such as offer(), peek(), poll(),
etc. Note: The default initial capacity of an ArrayList is pretty small. It is a
good habit to construct the ArrayList with a higher initial capacity. This can
avoid the resizing cost.
Example: ArrayList
Classification: Restricted Page 19
ArrayList al = new ArrayList();
al.add(3);
al.add(2);
al.add(1);
al.add(4);
al.add(5);
al.add(6);
al.add(6);
Iterator iter1 = al.iterator();
while(iter1.hasNext()){
System.out.println(iter1.next());
}
Example: ArrayList (Using Generics + Iterating
using Iterator and for-each loop)
Classification: Restricted Page 20
import java.util.*; class
TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
//Traversing using for-each loop
for(String obj:list)
System.out.println(obj);
}
}
User-defined class objects in Java ArrayList
Classification: Restricted Page 21
class Student{
int rollno;
String
name; int
age;
Student(int rollno,String name,int
age){ this.rollno=rollno;
this.name=name
; this.age=age;
}
}
import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects Student s1=new
Student(101,"Sonoo",23); Student s2=new
Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object al.add(s2);
al.add(s3);
//Getting Iterator Iterator
itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+"
"+st.age);
}
}
ArrayList Constructors
Classification: Restricted Page 22
ArrayList Methods
Classification: Restricted Page 23
Example of addAll(Collection c) method
Classification: Restricted Page 24
import java.util.*;
class TestCollection4{
public static void main(String args[]){ ArrayList<String> al=new
ArrayList<String>(); al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>(); al2.add("Sonoo");
al2.add("Hanumat");
al.addAll(al2);//adding second list in first list
Iterator itr=al.iterator();
while(itr.hasNext()){ System.out.println(itr.next());
}
}
}
Example of removeAll() method
Classification: Restricted Page 25
import java.util.*; class
TestCollection5{
public static void main(String args[]){ ArrayList<String> al=new
ArrayList<String>(); al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>(); al2.add("Ravi");
al2.add("Hanumat");
al.removeAll(al2);
System.out.println("iterating the elements after removing the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Example of retainAll()
Classification: Restricted Page 26
import java.util.*; class
TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Exercise…
Classification: Restricted Page 27
• Write a class “Book” that takes as members id, name, author, publisher and
quantity.
• Write a program for creating an ArrayList of Books. Add 5 books to the list.
• Iterate through the list and print all the properties of the books.
Exercise… ListIterator
Classification: Restricted Page 28
• What is a ListIterator?
• When we already have Iterator, why do we need ListIterator? What are the
advantages?
Exercise: ArrayList Hierarchy
The ArrayList Hierarchy is shown. Go
through the Java API on Oracle’s site and
draw the hierarchy for all collections
discussed in class today.
Classification: Restricted Page 29
LinkedList
Classification: Restricted Page 30
• Uses doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque
interfaces
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs to
be occurred.
• Java LinkedList class can be used as list, stack or queue.
LinkedList constructors
Classification: Restricted Page 31
LinkedList Methods
Classification: Restricted Page 32
Example: LinkedList
Classification: Restricted Page 33
LinkedList ll = new LinkedList();
ll.add(3);
ll.add(2);
ll.add(1);
ll.add(4);
ll.add(5);
ll.add(6);
ll.add(6);
Iterator iter2 = al.iterator();
while(iter2.hasNext()){
System.out.println(iter2.next());
}
Exercise: LinkedList
Classification: Restricted Page 34
Implement all the program examples written for ArrayList with LinkedList.
Performance: ArrayList vs LinkedList
Classification: Restricted Page 35
ArrayList arrayList = new ArrayList();
LinkedList linkedList = new LinkedList();
// ArrayList add
long startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
arrayList.add(i);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("ArrayList add: " + duration);
// LinkedList add
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
linkedList.add(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList add: " + duration);
// ArrayList get
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
arrayList.get(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("ArrayList get: " + duration);
// LinkedList get
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
linkedList.get(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList get: " + duration);
// ArrayList remove
startTime = System.nanoTime();
for (int i = 9999; i >=0; i--) {
arrayList.remove(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("ArrayList remove: " + duration);
// LinkedList remove
startTime = System.nanoTime();
for (int i = 9999; i >=0; i--) {
linkedList.remove(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList remove: " + duration);
ArrayList vs LinkedList
Classification: Restricted Page 36
List Interface in Java
• public interface List<E> extends Collection<E>
Classification: Restricted Page 37
Java ListIterator Interface
• public interface ListIterator<E> extends Iterator<E>
• Can be used to traverse through the list in forward and backwards/reverse
direction
Classification: Restricted Page 38
Java ListIterator example
Classification: Restricted Page 39
import java.util.*;
public class TestCollection8{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
System.out.println("element at 2nd position: "+al.get(2));
ListIterator<String> itr=al.listIterator();
System.out.println("traversing elements in forward direction...");
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("traversing elements in backward direction...");
while(itr.hasPrevious()){
System.out.println(itr.previous());
}
}
}
Set Interface Context
Collection
Classification: Restricted Page 40
Set
Set Interface
• Same methods as Collection
• different contract - no duplicate entries
• Defines two fundamental methods
•boolean add(Object o) - rejectduplicates
•Iterator iterator()
• Provides an Iterator to step through the elements in the
Set
• No guaranteed order in the basic Set interface
• There is a SortedSet interface that extends Set
Classification: Restricted Page 41
HashSet and TreeSet Context
HashSet TreeSet
Classification: Restricted Page 42
Collection
Set
List vs Set
Classification: Restricted Page 43
• List can contain duplicate elements whereas Set contains unique elements
only.
HashSet
Classification: Restricted Page 44
• Find and add elements very quickly
• uses hashing implementation in HashMap
• Hashing uses an array of linked lists
• The hashCode() is used to index intothe array
• Then equals() is used to determine if element is in the(short) list of
elements at that index
• No order imposed on elements
• The hashCode()method and the equals()method must be compatible
• if two objects are equal, they must have the same hashCode()
value
HashSet constructors
Classification: Restricted Page 45
HashSet methods
Classification: Restricted Page 46
HashSet Example
Classification: Restricted Page 47
import java.util.*;
class TestCollection9{
public static void main(String args[]){
//Creating HashSet and adding elements HashSet<String> set=new
HashSet<String>(); set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
HashSet Example : Book
Classification: Restricted Page 48
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author,
String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us
C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data
Communications & Networking","Forouzan","Mc
Graw Hill",4);
Book b3=new Book(103,"Operating
System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+"
"+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Exercise…
Classification: Restricted Page 49
• What is LinkedHashSet?
• When would you use LinkedHashSet?
TreeSet
Classification: Restricted Page 50
• Elements can be inserted in any order
• The TreeSet stores them in order
• An iterator always presents them in order
• Default order is defined by natural order
• objects implement the Comparable interface
• TreeSet uses compareTo(Object o) tosort
• Can use a different Comparator
• provide Comparator to the TreeSet constructor
TreeSet constructor
Classification: Restricted Page 51
TreeSet Methods
Classification: Restricted Page 52
TreeSet Example
Classification: Restricted Page 53
import java.util.*;
class TestCollection11{
public static void main(String args[]){
//Creating and adding elements TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
TreeSet Example: Book
Classification: Restricted Page 54
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author,
String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class TreeSetExample {
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant
Kanetkar","BPB",8);
Book b2=new Book(233,"Operating
System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+"
"+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Thank You

More Related Content

PDF
Collections In Java
PPTX
Java - Collections framework
PDF
Java Collections Tutorials
PDF
Collections in Java Notes
PPSX
Collections - Lists, Sets
PDF
Java Collection framework
DOCX
Java collections notes
Collections In Java
Java - Collections framework
Java Collections Tutorials
Collections in Java Notes
Collections - Lists, Sets
Java Collection framework
Java collections notes

What's hot (20)

PDF
5 collection framework
PPT
Java Collections Framework
PPT
Java collection
PDF
07 java collection
PDF
Collections Api - Java
ODP
Java Collections
PPT
Collection Framework in java
PPT
Collections in Java
PPT
java collections
PPSX
Collections - Array List
PDF
Collections Java e Google Collections
PPT
Java collections concept
PDF
Java ArrayList Tutorial | Edureka
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PPTX
collection framework in java
PPSX
Collections - Maps
PDF
Java Collections API
DOCX
Array list
PDF
Scala Collections : Java 8 on Steroids
5 collection framework
Java Collections Framework
Java collection
07 java collection
Collections Api - Java
Java Collections
Collection Framework in java
Collections in Java
java collections
Collections - Array List
Collections Java e Google Collections
Java collections concept
Java ArrayList Tutorial | Edureka
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
collection framework in java
Collections - Maps
Java Collections API
Array list
Scala Collections : Java 8 on Steroids
Ad

Similar to Collections - Lists & sets (20)

PPTX
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
PPTX
collection framework.pptx
PPTX
Session 15 - Collections - Array List
PPTX
collectionsframework210616084411 (1).pptx
DOCX
ArrayList.docx
PDF
Collection framework (completenotes) zeeshan
PPTX
Collections lecture 35 40
PPTX
Session 17 - Collections - Lists, Sets
PPTX
Collections in object oriented programming
PPTX
Collections Array list
PPT
PDF
Java collections
PPT
List in java
PPT
12_-_Collections_Framework
PDF
java unit 4 pdf - about java collections
PPT
description of Collections, seaching & Sorting
PPT
Collection Framework.power point presentation.......
PPTX
Collections
PPT
Java Collection fundamentals and Uses Unit
PPTX
Nature Activities Binder _ by Slidesgo.pptx
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
collection framework.pptx
Session 15 - Collections - Array List
collectionsframework210616084411 (1).pptx
ArrayList.docx
Collection framework (completenotes) zeeshan
Collections lecture 35 40
Session 17 - Collections - Lists, Sets
Collections in object oriented programming
Collections Array list
Java collections
List in java
12_-_Collections_Framework
java unit 4 pdf - about java collections
description of Collections, seaching & Sorting
Collection Framework.power point presentation.......
Collections
Java Collection fundamentals and Uses Unit
Nature Activities Binder _ by Slidesgo.pptx
Ad

More from RatnaJava (13)

PPTX
Review Session and Attending Java Interviews
PPTX
Collections - Sorting, Comparing Basics
PPTX
Object Class
PPTX
Exception Handling
PPTX
OOPs with Java - Packaging and Access Modifiers
PPTX
OOP with Java - Abstract Classes and Interfaces
PPTX
OOP with Java - Part 3
PPTX
OOP with Java - continued
PPTX
Object Oriented Programming
PPTX
Data Handling and Function
PPTX
Introduction to Java Part-3
PPTX
Introduction to Java Part-2
PPTX
Introduction to Java
Review Session and Attending Java Interviews
Collections - Sorting, Comparing Basics
Object Class
Exception Handling
OOPs with Java - Packaging and Access Modifiers
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Part 3
OOP with Java - continued
Object Oriented Programming
Data Handling and Function
Introduction to Java Part-3
Introduction to Java Part-2
Introduction to Java

Recently uploaded (20)

PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
CloudStack 4.21: First Look Webinar slides
PPTX
Tartificialntelligence_presentation.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
The various Industrial Revolutions .pptx
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPT
Geologic Time for studying geology for geologist
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Unlock new opportunities with location data.pdf
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPT
What is a Computer? Input Devices /output devices
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
Modernising the Digital Integration Hub
Hindi spoken digit analysis for native and non-native speakers
O2C Customer Invoices to Receipt V15A.pptx
A novel scalable deep ensemble learning framework for big data classification...
Univ-Connecticut-ChatGPT-Presentaion.pdf
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
CloudStack 4.21: First Look Webinar slides
Tartificialntelligence_presentation.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Zenith AI: Advanced Artificial Intelligence
A comparative study of natural language inference in Swahili using monolingua...
The various Industrial Revolutions .pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Geologic Time for studying geology for geologist
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
observCloud-Native Containerability and monitoring.pptx
Unlock new opportunities with location data.pdf
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
What is a Computer? Input Devices /output devices
Chapter 5: Probability Theory and Statistics
Modernising the Digital Integration Hub

Collections - Lists & sets

  • 2. Page 2Classification: Restricted Agenda • List – ArrayList, LinkedList • Set – HashSet, LinkedHashSet, TreeSet
  • 4. Collection Interface Classification: Restricted Page 5 • Defines fundamental methods •int size(); •boolean isEmpty(); •boolean contains(Object element); •boolean add(Object element); // Optional •boolean remove(Object element); // Optional •Iterator iterator(); • These methods are enough to define the basic behavior of a collection • Provides an Iterator to step through the elements in the Collection
  • 5. Iterator Interface • Defines three fundamental methods •Object next() •boolean hasNext() •void remove() • These three methods provide access to the contents of the collection • An Iterator knows position within collection • Each call to next() “reads” an element from the collection • Then you can use it or removeit Classification: Restricted Page 6
  • 6. Example - SimpleCollection Classification: Restricted Page 7 public class SimpleCollection { public static void main(String[] args) { Collection c; c = new ArrayList(); System.out.println(c.getClass().getName()); for (int i=1; i <= 10; i++) { c.add(i + " * " + i + " ="+i*i); } Iterator iter = c.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } }
  • 7. List Interface Context Classification: Restricted Page 8 Collection List
  • 8. ListIterator Interface Classification: Restricted Page 9 • Extends the Iterator interface • Defines three fundamental methods • void add(Object o) - before current position • boolean hasPrevious() • Object previous() • The addition of these three methods defines the basic behavior of an ordered list • A ListIterator knows position within list
  • 9. ArrayList and LinkedList Context ArrayList LinkedList Classification: Restricted Page 10 Collection List
  • 10. List as part of Collection Classification: Restricted Page 11
  • 11. List Implementations Classification: Restricted Page 12 • ArrayList • low cost random access • high cost insert and delete • array that resizes if need be • LinkedList • sequential access • low cost insert and delete • high cost random access • Vector • Similar to ArrayList, but thread-safe
  • 12. ArrayList overview Classification: Restricted Page 13 • Constant time positional access (it’s an array) • One tuning parameter, the initial capacity public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException( "Illegal Capacity: "+initialCapacity); this.elementData = new Object[initialCapacity]; }
  • 13. ArrayList methods Classification: Restricted Page 14 • The indexed get and set methods of the List interface are appropriate to use since ArrayLists are backed by an array •Object get(int index) •Object set(int index, Object element) • Indexed add and remove are provided, but can be costly if used frequently •void add(int index, Object element) •Object remove(int index) • May want to resize in one shot if adding manyelements •void ensureCapacity(int minCapacity)
  • 14. LinkedList overview Classification: Restricted Page 15 • Stores each element in a node • Each node stores a link to the next and previousnodes • Insertion and removal are inexpensive • just update the links in the surrounding nodes • Linear traversal is inexpensive • Random access is expensive • Start from beginning or end and traverse each node while counting
  • 15. LinkedList entries Classification: Restricted Page 16 private static class Entry { Object element; Entry next; Entry previous; Entry(Object element, Entry next, Entry previous) { this.element = element; this.next = next; this.previous = previous; } } private Entry header = new Entry(null, null, null); public LinkedList() { header.next = header.previous = header; }
  • 16. LinkedList methods Classification: Restricted Page 17 • The list is sequential, so access it that way •ListIterator listIterator() • ListIterator knows about position • use add() from ListIterator to add at a position • use remove() from ListIterator to remove at a position • LinkedList knows a few things too •void addFirst(Object o), void addLast(Object o) •Object getFirst(), Object getLast() •Object removeFirst(), Object removeLast()
  • 17. ArrayList vs. LinkedList vs. Vector Classification: Restricted Page 18 From the hierarchy diagram, they all implement List interface. They are very similar to use. Their main difference is their implementation which causes different performance for different operations. ArrayList is implemented as a resizable array. As more elements are added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array. LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods. Vector is similar with ArrayList, but it is synchronized. ArrayList is a better choice if your program is thread- safe. Vector and ArrayList require space as more elements are added. Vector each time doubles its array size, while ArrayList grow 50% of its size each time. LinkedList, however, also implements Queue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc. Note: The default initial capacity of an ArrayList is pretty small. It is a good habit to construct the ArrayList with a higher initial capacity. This can avoid the resizing cost.
  • 18. Example: ArrayList Classification: Restricted Page 19 ArrayList al = new ArrayList(); al.add(3); al.add(2); al.add(1); al.add(4); al.add(5); al.add(6); al.add(6); Iterator iter1 = al.iterator(); while(iter1.hasNext()){ System.out.println(iter1.next()); }
  • 19. Example: ArrayList (Using Generics + Iterating using Iterator and for-each loop) Classification: Restricted Page 20 import java.util.*; class TestCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } //Traversing using for-each loop for(String obj:list) System.out.println(obj); } }
  • 20. User-defined class objects in Java ArrayList Classification: Restricted Page 21 class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name ; this.age=age; } } import java.util.*; public class TestCollection3{ public static void main(String args[]){ //Creating user-defined class objects Student s1=new Student(101,"Sonoo",23); Student s2=new Student(102,"Ravi",21); Student s2=new Student(103,"Hanumat",25); //creating arraylist ArrayList<Student> al=new ArrayList<Student>(); al.add(s1);//adding Student class object al.add(s2); al.add(s3); //Getting Iterator Iterator itr=al.iterator(); //traversing elements of ArrayList object while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } }
  • 23. Example of addAll(Collection c) method Classification: Restricted Page 24 import java.util.*; class TestCollection4{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Sonoo"); al2.add("Hanumat"); al.addAll(al2);//adding second list in first list Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 24. Example of removeAll() method Classification: Restricted Page 25 import java.util.*; class TestCollection5{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Ravi"); al2.add("Hanumat"); al.removeAll(al2); System.out.println("iterating the elements after removing the elements of al2..."); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 25. Example of retainAll() Classification: Restricted Page 26 import java.util.*; class TestCollection6{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ajay"); ArrayList<String> al2=new ArrayList<String>(); al2.add("Ravi"); al2.add("Hanumat"); al.retainAll(al2); System.out.println("iterating the elements after retaining the elements of al2..."); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 26. Exercise… Classification: Restricted Page 27 • Write a class “Book” that takes as members id, name, author, publisher and quantity. • Write a program for creating an ArrayList of Books. Add 5 books to the list. • Iterate through the list and print all the properties of the books.
  • 27. Exercise… ListIterator Classification: Restricted Page 28 • What is a ListIterator? • When we already have Iterator, why do we need ListIterator? What are the advantages?
  • 28. Exercise: ArrayList Hierarchy The ArrayList Hierarchy is shown. Go through the Java API on Oracle’s site and draw the hierarchy for all collections discussed in class today. Classification: Restricted Page 29
  • 29. LinkedList Classification: Restricted Page 30 • Uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces • Java LinkedList class can contain duplicate elements. • Java LinkedList class maintains insertion order. • Java LinkedList class is non synchronized. • In Java LinkedList class, manipulation is fast because no shifting needs to be occurred. • Java LinkedList class can be used as list, stack or queue.
  • 32. Example: LinkedList Classification: Restricted Page 33 LinkedList ll = new LinkedList(); ll.add(3); ll.add(2); ll.add(1); ll.add(4); ll.add(5); ll.add(6); ll.add(6); Iterator iter2 = al.iterator(); while(iter2.hasNext()){ System.out.println(iter2.next()); }
  • 33. Exercise: LinkedList Classification: Restricted Page 34 Implement all the program examples written for ArrayList with LinkedList.
  • 34. Performance: ArrayList vs LinkedList Classification: Restricted Page 35 ArrayList arrayList = new ArrayList(); LinkedList linkedList = new LinkedList(); // ArrayList add long startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { arrayList.add(i); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("ArrayList add: " + duration); // LinkedList add startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { linkedList.add(i); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("LinkedList add: " + duration); // ArrayList get startTime = System.nanoTime(); for (int i = 0; i < 10000; i++) { arrayList.get(i); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("ArrayList get: " + duration); // LinkedList get startTime = System.nanoTime(); for (int i = 0; i < 10000; i++) { linkedList.get(i); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("LinkedList get: " + duration); // ArrayList remove startTime = System.nanoTime(); for (int i = 9999; i >=0; i--) { arrayList.remove(i); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("ArrayList remove: " + duration); // LinkedList remove startTime = System.nanoTime(); for (int i = 9999; i >=0; i--) { linkedList.remove(i); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("LinkedList remove: " + duration);
  • 36. List Interface in Java • public interface List<E> extends Collection<E> Classification: Restricted Page 37
  • 37. Java ListIterator Interface • public interface ListIterator<E> extends Iterator<E> • Can be used to traverse through the list in forward and backwards/reverse direction Classification: Restricted Page 38
  • 38. Java ListIterator example Classification: Restricted Page 39 import java.util.*; public class TestCollection8{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Amit"); al.add("Vijay"); al.add("Kumar"); al.add(1,"Sachin"); System.out.println("element at 2nd position: "+al.get(2)); ListIterator<String> itr=al.listIterator(); System.out.println("traversing elements in forward direction..."); while(itr.hasNext()){ System.out.println(itr.next()); } System.out.println("traversing elements in backward direction..."); while(itr.hasPrevious()){ System.out.println(itr.previous()); } } }
  • 40. Set Interface • Same methods as Collection • different contract - no duplicate entries • Defines two fundamental methods •boolean add(Object o) - rejectduplicates •Iterator iterator() • Provides an Iterator to step through the elements in the Set • No guaranteed order in the basic Set interface • There is a SortedSet interface that extends Set Classification: Restricted Page 41
  • 41. HashSet and TreeSet Context HashSet TreeSet Classification: Restricted Page 42 Collection Set
  • 42. List vs Set Classification: Restricted Page 43 • List can contain duplicate elements whereas Set contains unique elements only.
  • 43. HashSet Classification: Restricted Page 44 • Find and add elements very quickly • uses hashing implementation in HashMap • Hashing uses an array of linked lists • The hashCode() is used to index intothe array • Then equals() is used to determine if element is in the(short) list of elements at that index • No order imposed on elements • The hashCode()method and the equals()method must be compatible • if two objects are equal, they must have the same hashCode() value
  • 46. HashSet Example Classification: Restricted Page 47 import java.util.*; class TestCollection9{ public static void main(String args[]){ //Creating HashSet and adding elements HashSet<String> set=new HashSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); //Traversing elements Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 47. HashSet Example : Book Classification: Restricted Page 48 import java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class HashSetExample { public static void main(String[] args) { HashSet<Book> set=new HashSet<Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to HashSet set.add(b1); set.add(b2); set.add(b3); //Traversing HashSet for(Book b:set){ System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } }
  • 48. Exercise… Classification: Restricted Page 49 • What is LinkedHashSet? • When would you use LinkedHashSet?
  • 49. TreeSet Classification: Restricted Page 50 • Elements can be inserted in any order • The TreeSet stores them in order • An iterator always presents them in order • Default order is defined by natural order • objects implement the Comparable interface • TreeSet uses compareTo(Object o) tosort • Can use a different Comparator • provide Comparator to the TreeSet constructor
  • 52. TreeSet Example Classification: Restricted Page 53 import java.util.*; class TestCollection11{ public static void main(String args[]){ //Creating and adding elements TreeSet<String> al=new TreeSet<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); //Traversing elements Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
  • 53. TreeSet Example: Book Classification: Restricted Page 54 import java.util.*; class Book implements Comparable<Book>{ int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } public int compareTo(Book b) { if(id>b.id){ return 1; }else if(id<b.id){ return -1; }else{ return 0; } } } public class TreeSetExample { public static void main(String[] args) { Set<Book> set=new TreeSet<Book>(); //Creating Books Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(233,"Operating System","Galvin","Wiley",6); Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); //Adding Books to TreeSet set.add(b1); set.add(b2); set.add(b3); //Traversing TreeSet for(Book b:set){ System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } }