SlideShare a Scribd company logo
Java & JEE Training
Day 17 – Collections – Lists, Sets
Page 1Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 1
Quick Recap…
• How to define a class completely
• Define a POJO
• Define private data members
• Define public getters and setters
• Override
• toString() for more meaningful logging and printing
• equals() for search in a collection
• hashCode() for providing hashing function
• Comparison logic
• java.lang.Comparable interface - DEFAULT
• java.util.Comparator interface – A Comparator class for every
comparison logic
Page 2Classification: Restricted
Agenda…
• List – ArrayList, LinkedList
• Set – HashSet, LinkedHashSet, TreeSet
Java & JEE Training
Collections
Page 4Classification: Restricted
Collections Framework Diagram
Page 5Classification: Restricted
Collection Interface
• 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
Page 6Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 6
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 remove it
Page 7Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 7
Example - SimpleCollection
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());
}
}
Page 8Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 8
List Interface Context
Collection
List
Page 9Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 9
ListIterator Interface
• 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
Page 10Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 10
ArrayList and LinkedList Context
ArrayList LinkedList
Collection
List
Page 11Classification: Restricted
List as part of Collection
Page 12Classification: Restricted
List Implementations
• 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
Page 13Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 13
ArrayList overview
• 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];
}
Page 14Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 14
ArrayList methods
• 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 many elements
• void ensureCapacity(int minCapacity)
Page 15Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 15
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and previous nodes
• 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
Page 16Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 16
LinkedList entries
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;
}
Page 17Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 17
LinkedList methods
• 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()
Page 18Classification: Restricted
ArrayList vs. LinkedList vs. Vector
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.
Page 19Classification: Restricted
Example: ArrayList
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());
}
Page 20Classification: Restricted
Example: ArrayList (Using Generics + Iterating using Iterator
and for-each loop)
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);
}
}
Page 21Classification: Restricted
User-defined class objects in Java ArrayList
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);
}
}
}
Page 22Classification: Restricted
ArrayList Constructors
Page 23Classification: Restricted
ArrayList Methods
Page 24Classification: Restricted
Example of addAll(Collection c) method
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());
}
}
}
Page 25Classification: Restricted
Example of removeAll() method
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());
}
}
}
Page 26Classification: Restricted
Example of retainAll()
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());
}
}
}
Page 27Classification: Restricted
Exercise…
• 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.
Page 28Classification: Restricted
Exercise… ListIterator
• What is a ListIterator?
• When we already have Iterator, why do we need ListIterator? What are the
advantages?
Page 29Classification: Restricted
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.
Page 30Classification: Restricted
LinkedList
• 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.
Page 31Classification: Restricted
LinkedList constructors
Page 32Classification: Restricted
LinkedList Methods
Page 33Classification: Restricted
Example: LinkedList
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());
}
Page 34Classification: Restricted
Exercise: LinkedList
Implement all the program examples written for ArrayList with LinkedList.
Page 35Classification: Restricted
Performance: ArrayList vs LinkedList
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);
Page 36Classification: Restricted
ArrayList vs LinkedList
Page 37Classification: Restricted
List Interface in Java
• public interface List<E> extends Collection<E>
Page 38Classification: Restricted
Java ListIterator Interface
• public interface ListIterator<E> extends Iterator<E>
• Can be used to traverse through the list in forward and backwards/reverse
direction
Page 39Classification: Restricted
Java ListIterator example
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());
}
}
}
Page 40Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 40
Set Interface Context
Collection
Set
Page 41Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 41
Set Interface
• Same methods as Collection
• different contract - no duplicate entries
• Defines two fundamental methods
• boolean add(Object o) - reject duplicates
• 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
Page 42Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 42
HashSet and TreeSet Context
HashSet TreeSet
Collection
Set
Page 43Classification: Restricted
List vs Set
• List can contain duplicate elements whereas Set contains unique elements
only.
Page 44Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 44
HashSet
• Find and add elements very quickly
• uses hashing implementation in HashMap
• Hashing uses an array of linked lists
• The hashCode() is used to index into the 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
Page 45Classification: Restricted
HashSet constructors
Page 46Classification: Restricted
HashSet methods
Page 47Classification: Restricted
HashSet Example
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());
}
}
}
Page 48Classification: Restricted
HashSet Example : Book
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);
}
}
}
Page 49Classification: Restricted
Exercise…
• What is LinkedHashSet?
• When would you use LinkedHashSet?
Page 50Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 50
TreeSet
• 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) to sort
• Can use a different Comparator
• provide Comparator to the TreeSet constructor
Page 51Classification: Restricted
TreeSet constructor
Page 52Classification: Restricted
TreeSet Methods
Page 53Classification: Restricted
TreeSet Example
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());
}
}
}
Page 54Classification: Restricted
TreeSet Example: Book
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);
}
}
}
Page 55Classification: Restricted
Topics to be covered in next session
• Interview preparation, tips & tricks
Page 56Classification: Restricted
Thank you!

More Related Content

What's hot

Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
sets and maps
 sets and maps sets and maps
sets and maps
Rajkattamuri
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)
charan kumar
 
Java Collections
Java  Collections Java  Collections
Generics
GenericsGenerics
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
François Garillot
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
Rahul Sharma
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Collections Array list
Collections Array listCollections Array list
Collections Array list
RatnaJava
 
Sets
SetsSets
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
STL in C++
STL in C++STL in C++
STL in C++
Surya Prakash Sahu
 

What's hot (20)

Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Java Collection
Java CollectionJava Collection
Java Collection
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Generics
GenericsGenerics
Generics
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections Array list
Collections Array listCollections Array list
Collections Array list
 
Lecture-05-DSA
Lecture-05-DSALecture-05-DSA
Lecture-05-DSA
 
Sets
SetsSets
Sets
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
STL in C++
STL in C++STL in C++
STL in C++
 

Similar to Session 17 - Collections - Lists, Sets

Collectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.pptCollectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.ppt
swapnilslide2019
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
NaitikChatterjee
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
Collections
CollectionsCollections
Collections
Manav Prasad
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
Muthukumaran Subramanian
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
IllllBikkySharmaIlll
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
michael.labriola
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
ssuseredfbe9
 
Java util
Java utilJava util
Java util
Srikrishna k
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
ManojKandhasamy1
 

Similar to Session 17 - Collections - Lists, Sets (20)

Collectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.pptCollectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.ppt
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
Collections
CollectionsCollections
Collections
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collections
CollectionsCollections
Collections
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Java util
Java utilJava util
Java util
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Collections
CollectionsCollections
Collections
 

More from PawanMM

Session 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAXSession 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAX
PawanMM
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVC
PawanMM
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
PawanMM
 
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationSession 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
PawanMM
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate Integration
PawanMM
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 Introduction
PawanMM
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
PawanMM
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
PawanMM
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
PawanMM
 
Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)
PawanMM
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
PawanMM
 
Session 35 - Design Patterns
Session 35 - Design PatternsSession 35 - Design Patterns
Session 35 - Design Patterns
PawanMM
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
PawanMM
 
Session 33 - Session Management using other Techniques
Session 33 - Session Management using other TechniquesSession 33 - Session Management using other Techniques
Session 33 - Session Management using other Techniques
PawanMM
 
Session 32 - Session Management using Cookies
Session 32 - Session Management using CookiesSession 32 - Session Management using Cookies
Session 32 - Session Management using Cookies
PawanMM
 
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web AppsSession 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
PawanMM
 
Session 30 - Servlets - Part 6
Session 30 - Servlets - Part 6Session 30 - Servlets - Part 6
Session 30 - Servlets - Part 6
PawanMM
 
Session 29 - Servlets - Part 5
Session 29 - Servlets - Part 5Session 29 - Servlets - Part 5
Session 29 - Servlets - Part 5
PawanMM
 
Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4
PawanMM
 

More from PawanMM (20)

Session 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAXSession 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAX
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVC
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationSession 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate Integration
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 Introduction
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
 
Session 35 - Design Patterns
Session 35 - Design PatternsSession 35 - Design Patterns
Session 35 - Design Patterns
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
 
Session 33 - Session Management using other Techniques
Session 33 - Session Management using other TechniquesSession 33 - Session Management using other Techniques
Session 33 - Session Management using other Techniques
 
Session 32 - Session Management using Cookies
Session 32 - Session Management using CookiesSession 32 - Session Management using Cookies
Session 32 - Session Management using Cookies
 
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web AppsSession 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
 
Session 30 - Servlets - Part 6
Session 30 - Servlets - Part 6Session 30 - Servlets - Part 6
Session 30 - Servlets - Part 6
 
Session 29 - Servlets - Part 5
Session 29 - Servlets - Part 5Session 29 - Servlets - Part 5
Session 29 - Servlets - Part 5
 
Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4
 

Recently uploaded

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
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
 
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
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
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
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
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
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 

Recently uploaded (20)

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
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
 
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...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
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...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
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
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

Session 17 - Collections - Lists, Sets

  • 1. Java & JEE Training Day 17 – Collections – Lists, Sets
  • 2. Page 1Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 1 Quick Recap… • How to define a class completely • Define a POJO • Define private data members • Define public getters and setters • Override • toString() for more meaningful logging and printing • equals() for search in a collection • hashCode() for providing hashing function • Comparison logic • java.lang.Comparable interface - DEFAULT • java.util.Comparator interface – A Comparator class for every comparison logic
  • 3. Page 2Classification: Restricted Agenda… • List – ArrayList, LinkedList • Set – HashSet, LinkedHashSet, TreeSet
  • 4. Java & JEE Training Collections
  • 6. Page 5Classification: Restricted Collection Interface • 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
  • 7. Page 6Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 6 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 remove it
  • 8. Page 7Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 7 Example - SimpleCollection 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()); } }
  • 9. Page 8Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 8 List Interface Context Collection List
  • 10. Page 9Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 9 ListIterator Interface • 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
  • 11. Page 10Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 10 ArrayList and LinkedList Context ArrayList LinkedList Collection List
  • 12. Page 11Classification: Restricted List as part of Collection
  • 13. Page 12Classification: Restricted List Implementations • 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
  • 14. Page 13Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 13 ArrayList overview • 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]; }
  • 15. Page 14Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 14 ArrayList methods • 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 many elements • void ensureCapacity(int minCapacity)
  • 16. Page 15Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 15 LinkedList overview • Stores each element in a node • Each node stores a link to the next and previous nodes • 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
  • 17. Page 16Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 16 LinkedList entries 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; }
  • 18. Page 17Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 17 LinkedList methods • 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()
  • 19. Page 18Classification: Restricted ArrayList vs. LinkedList vs. Vector 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.
  • 20. Page 19Classification: Restricted Example: ArrayList 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()); }
  • 21. Page 20Classification: Restricted Example: ArrayList (Using Generics + Iterating using Iterator and for-each loop) 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); } }
  • 22. Page 21Classification: Restricted User-defined class objects in Java ArrayList 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); } } }
  • 25. Page 24Classification: Restricted Example of addAll(Collection c) method 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()); } } }
  • 26. Page 25Classification: Restricted Example of removeAll() method 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()); } } }
  • 27. Page 26Classification: Restricted Example of retainAll() 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()); } } }
  • 28. Page 27Classification: Restricted Exercise… • 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.
  • 29. Page 28Classification: Restricted Exercise… ListIterator • What is a ListIterator? • When we already have Iterator, why do we need ListIterator? What are the advantages?
  • 30. Page 29Classification: Restricted 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.
  • 31. Page 30Classification: Restricted LinkedList • 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.
  • 34. Page 33Classification: Restricted Example: LinkedList 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()); }
  • 35. Page 34Classification: Restricted Exercise: LinkedList Implement all the program examples written for ArrayList with LinkedList.
  • 36. Page 35Classification: Restricted Performance: ArrayList vs LinkedList 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);
  • 38. Page 37Classification: Restricted List Interface in Java • public interface List<E> extends Collection<E>
  • 39. Page 38Classification: Restricted Java ListIterator Interface • public interface ListIterator<E> extends Iterator<E> • Can be used to traverse through the list in forward and backwards/reverse direction
  • 40. Page 39Classification: Restricted Java ListIterator example 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()); } } }
  • 41. Page 40Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 40 Set Interface Context Collection Set
  • 42. Page 41Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 41 Set Interface • Same methods as Collection • different contract - no duplicate entries • Defines two fundamental methods • boolean add(Object o) - reject duplicates • 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
  • 43. Page 42Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 42 HashSet and TreeSet Context HashSet TreeSet Collection Set
  • 44. Page 43Classification: Restricted List vs Set • List can contain duplicate elements whereas Set contains unique elements only.
  • 45. Page 44Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 44 HashSet • Find and add elements very quickly • uses hashing implementation in HashMap • Hashing uses an array of linked lists • The hashCode() is used to index into the 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
  • 48. Page 47Classification: Restricted HashSet Example 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()); } } }
  • 49. Page 48Classification: Restricted HashSet Example : Book 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); } } }
  • 50. Page 49Classification: Restricted Exercise… • What is LinkedHashSet? • When would you use LinkedHashSet?
  • 51. Page 50Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 50 TreeSet • 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) to sort • Can use a different Comparator • provide Comparator to the TreeSet constructor
  • 54. Page 53Classification: Restricted TreeSet Example 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()); } } }
  • 55. Page 54Classification: Restricted TreeSet Example: Book 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); } } }
  • 56. Page 55Classification: Restricted Topics to be covered in next session • Interview preparation, tips & tricks