0% found this document useful (0 votes)
5 views

Lecture 28, 29, 30 Collection Framework in Java

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 28, 29, 30 Collection Framework in Java

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 133

Collection Framework

in Java
UNIT IV
Object Class

Object

Arrays Collections

All interfaces are marked with <interface> tag in the diagram. Yellow boxes represent classes
implements extends
Introduction
• The Java platform includes a collections framework. A collection is an object that represents a group of objects
(such as the classic Vector class). A collections framework is a unified architecture for representing and
manipulating collections, enabling collections to be manipulated independently of implementation details.The
primary advantages of a collections framework are that it:
• Reduces programming effort by providing data structures and algorithms so you don't have to write them
yourself.
• Increases performance by providing high-performance implementations of data structures and algorithms.
Because the various implementations of each interface are interchangeable, programs can be tuned by
switching implementations.
• Provides interoperability between unrelated APIs by establishing a common language to pass collections back
and forth.
• Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
• Reduces the effort required to design and implement APIs by not requiring you to produce ad hoc collections
APIs.
• Fosters software reuse by providing a standard interface for collections and algorithms with which to
manipulate them.
The collections framework
• Collection interfaces. Represent different types of collections, such as sets, lists, and maps. These interfaces form
the basis of the framework.
• General-purpose implementations. Primary implementations of the collection interfaces.
• Legacy implementations. The collection classes from earlier releases, Vector and Hashtable, were retrofitted to
implement the collection interfaces.
• Special-purpose implementations. Implementations designed for use in special situations. These implementations
display nonstandard performance characteristics, usage restrictions, or behavior.
• Concurrent implementations. Implementations designed for highly concurrent use.
• Wrapper implementations. Add functionality, such as synchronization, to other implementations.
• Convenience implementations. High-performance "mini-implementations" of the collection interfaces.
• Abstract implementations. Partial implementations of the collection interfaces to facilitate custom
implementations.
• Algorithms. Static methods that perform useful functions on collections, such as sorting a list.
• Infrastructure. Interfaces that provide essential support for the collection interfaces.
• Array Utilities. Utility functions for arrays of primitive types and reference objects. Not, strictly speaking, a part of
the collections framework, this feature was added to the Java platform at the same time as the collections
framework and relies on some of the same infrastructure.
Collection Interface
Collection
<interface>

Set List Queue


<interface> <interface> <interface>

SortedSet
<interface>

HashSet LinkedHashSet TreeSet ArrayList Vector LinkedList PriorityQueue

All interfaces are marked with <interface> tag in the diagram. Yellow boxes represent classes
implements extends
java.util.Collection
•java.util.Set
•java.util.SortedSet
•java.util.NavigableSet
•java.util.Queue
•java.util.concurrent.BlockingQueue
•java.util.concurrent.TransferQueue
•java.util.Deque
•java.util.concurrent.BlockingDeque
Map Interface

Map
<interface>

SortedMap
<interface>

Hashtable LinkedHashMap HashMap TreeMap

All interfaces are marked with <interface> tag in the diagram. Yellow boxes represent classes
implements extends
java.util.Map
• java.util.SortedMap
• java.util.NavigableMap
• java.util.concurrent.ConcurrentMap
• java.util.concurrent.ConcurrentNavigableMap
Collection Implementation
Hash Table +
Interface Hash Table Resizable Array Balanced Tree Linked List
Linked List
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Deque ArrayDeque LinkedList
Map HashMap TreeMap LinkedHashMap

Classes that implement the collection interfaces typically have names in the form of
<Implementation-style><Interface>

• Each collection class implements an interface from a hierarchy


• Each class is designed for a specific type of storage
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
Iterator Interface
• Defines three fundamental methods
• Object next() - it returns the element and moves the cursor pointer to the next element
• boolean hasNext() - it returns true if iterator has more elements.
• void remove() - it removes the last elements returned by the iterator. It is rarely used.
• 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
Methods of Collection interface
No. Method Description

1 public boolean add(Object element) is used to insert an element in this collection.

2 public boolean addAll(collection c) is used to insert the specified collection elements in the
invoking collection.

3 public boolean remove(Object element) is used to delete an element from this collection.

is used to delete all the elements of specified collection from


4 public boolean removeAll(Collection c) the invoking collection.

is used to delete all the elements of invoking collection except


5 public boolean retainAll(Collection c) the specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

12
Methods of Collection interface
No. Method Description

8 public boolean contains(object element) is used to search an element.

9 public boolean containsAll(Collection c) is used to search the specified collection in this collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object element) matches two collection.

14 public int hashCode() returns the hashcode number for collection.

13
Lists and Sets
• Ordered Lists

• ArrayList
• Stores a list of items in a dynamically sized array

• LinkedList
• Allows speedy insertion and removal of items from the list

A list is a collection that maintains the order


of its elements.
ArrayList class
• Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and
implements List interface.

• Java ArrayList class can contain duplicate elements.


• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
• To make synchronized
List<String> syncal =Collections.synchronizedList(new ArrayList<String>());

15
Example of Java ArrayList class

import java.util.*;
class TestCollection1{
public static void main(String args[]){
OUTPUT:
ArrayList<String> al=new ArrayList<String>();//creating arraylist Ravi
al.add("Ravi");//adding object in arraylist Vijay
al.add("Vijay"); Ravi
al.add("Ravi");
Ajay
al.add("Ajay");

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements


while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

16
Methods of ArrayList class
• 1) add( Object o):
This method adds an object o to the arraylist.
obj.add("hello");
This statement would add a string hello in the arraylist at last position.

• 2) add(int index, Object o): It adds the object o to the array list at the given index.
obj.add(2, "bye");
It will add the string bye to the 2nd index (3rd position as the array list starts with index 0) of
array list.
• 3) remove(Object o): Removes the object o from the ArrayList.
obj.remove("Chaitanya");
This statement will remove the string “Chaitanya” from the ArrayList.

17
Methods of ArrayList class

• 4) remove(int index): Removes element from a given index.


obj.remove(3);
It would remove the element of index 3 (4th element of the list – List
starts with o).
• 5) set(int index, Object o): Used for updating an element. It replaces the
element present at the specified index with the object o.
obj.set(2, "Tom");
It would replace the 3rd element (index =2 is 3rd element) with the value
Tom.

18
Methods of ArrayList class
• 6) int indexOf(Object o): Gives the index of the object o. If the element is
not found in the list then this method returns the value -1.
int pos = obj.indexOf("Tom");
This would give the index (position) of the string Tom in the list.
• 7) Object get(int index): It returns the object of list which is present at
the specified index.
String str= obj.get(2);
Function get would return the string stored at 3rd position (index 2).

19
Methods of ArrayList class

• 8) int size(): It gives the size of the ArrayList – Number of elements of the list.
int numberofitems = obj.size();
• 9) boolean contains(Object o): It checks whether the given object o is present in the array list if
its there then it returns true else it returns false.
obj.contains("Steve");
• 10) clear(): It is used for removing all the elements of the array list in one go.
obj.clear();

20
Iterate the elements of
collection

• Two ways
• By Iterator interface.
• By for-each loop.

21
Iterating the elements of Collection by for-each
loop

import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>(); OUTPUT:
al.add("Ravi"); Ravi
al.add("Vijay"); Vijay
al.add("Ravi"); Ravi
al.add("Ajay"); Ajay
for(String obj:al)
System.out.println(obj);
}
}

22
Iterating the elements of Collection
by Iterator interface
class Student{ import java.util.*;
int rollno; public class TestCollection3{
String name; public static void main(String args[]){
int age; //Creating user-defined class objects
Student(int rollno,String name,int age){ Student s1=new Student(101,"Sonoo",23);
this.rollno=rollno; Student s2=new Student(102,"Ravi",21);
this.name=name; Student s2=new Student(103,"Hanumat",25);
this.age=age;
} ArrayList<Student> al=new ArrayList<Student>();//creating
} arraylist
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);

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);
OUTPUT: }
101 Sonoo 23 }
102 Ravi 21 }

103 Hanumat 25 23
How to iterate arraylist elements using
Enumeration interface
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;

public class EnumExample { Output:


public static void main(String[] args) {
//create an ArrayList object
ArrayList<String> arrayList = new ArrayList<String>(); ArrayList elements:
//Add elements to ArrayList C
arrayList.add("C"); C++
arrayList.add("C++");
arrayList.add("Java"); Java
arrayList.add("DotNet"); DotNet
arrayList.add("Perl"); Perl
// Get the Enumeration object
Enumeration<String> e = Collections.enumeration(arrayList);

// Enumerate through the ArrayList elements


System.out.println("ArrayList elements: ");
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
24
Example of addAll(Collection c)
method
import java.util.*;
class TestCollection4{
public static void main(String args[]){
OUTPUT:
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); Ravi
al.add("Vijay"); Vijay
al.add("Ajay"); Ajay
ArrayList<String> al2=new ArrayList<String>(); Sonoo
al2.add("Sonoo"); Hanumat
al2.add("Hanumat");

al.addAll(al2);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

25
Loop in ArrayList
//Part 1 //Part 2
import java.util.*;
public class LoopExample { /* While Loop for iterating ArrayList*/
public static void main(String[] args) {
System.out.println("While Loop");
ArrayList<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(14); int count = 0;
arrlist.add(7); while (arrlist.size() > count) {
arrlist.add(39);
arrlist.add(40); System.out.println(arrlist.get(count));
count++;
/* For Loop for iterating ArrayList */ }
System.out.println("For Loop");
for (int counter = 0; counter < arrlist.size(); counter++) { /*Looping Array List using Iterator*/
System.out.println("Iterator");
System.out.println(arrlist.get(counter)); Iterator iter = arrlist.iterator();
} while (iter.hasNext()) {
System.out.println(iter.next());
/* Advanced For Loop*/ }
System.out.println("Advanced For Loop"); }
for (Integer num : arrlist) { }
System.out.println(num);
}

26
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("iteration after removing the elements of al2...");


Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
OUTPUT:
} iteration after removing the elements of al2...
} Vijay
Ajay 27
Example of retainAll() method
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());
}
}
}
OUTPUT:
iterating the elements after retaining the elements of al2...
Ravi

28
Lists and Sets
• Unordered Sets

• HashSet
• Uses hash tables to speed up finding, adding, and removing
elements
• TreeSet
• Uses a binary tree to speed up finding, adding, and removing
elements

A set is an unordered collection of unique


elements.
Stacks and Queues
• Another way of gaining efficiency in a collection is
to reduce the number of operations available
• Two examples are:
• Stack
• Remembers the order of its elements, but it does not
allow you to insert elements in every position
• You can only add and remove elements at the top
• Queue
• Add items to one end (the tail)
• Remove them from the other end (the head)
• Example: A line of people waiting for a bank teller
Maps
• A map stores keys, values, and the associations between
them
• Example:
• Barcode keys and books
A map keeps associations
between key and value objects.

• Keys
• Provides an easy way to represent an object (such as a numeric
bar code)
• Values
• The actual object that is associated with the key
The Collection Interface (1)
• List, Queue and Set are specialized interfaces that
inherit from the Collection interface
• All share the following commonly used methods
The Collection Interface (2)
Linked Lists
• Linked lists use references to maintain an ordered lists
of ‘nodes’
• The ‘head’ of the list references the first node
• Each node has a value and a reference to the next node

• They can be used to implement


• A List Interface
• A Queue Interface
Linked Lists Operations
• Efficient Operations
• Insertion of a node
• Find the elements it goes between
• Remap the references

• Removal of a node
• Find the element to remove
• Remap neighbor’s references

• Visiting all elements in order

• Inefficient Operations
• Random access
Each instance variable is declared just
like other variables we have used.
LinkedList: Important
Methods
Generic Linked Lists

• The Collection Framework uses Generics


• Each list is declared with a type field in < > angle brackets

LinkedList<String> employeeNames = . . .;

LinkedList<String>
LinkedList<Employee>
List Iterators
When traversing a LinkedList, use a ListIterator
 Keeps track of where you are in the list.

LinkedList<String> employeeNames = . . .;
ListIterator<String> iter = employeeNames.listIterator()

Use an iterator to:


 Access elements inside a linked list
 Visit other than the first and the last nodes
Using Iterators
• Think of an iterator as pointing between two
elements
ListIterator<String> iter =
myList.listIterator()

iterator.next();

iterator.add(“J”)
;

 Note that the generic type for the listIterator


must match the generic type of the LinkedList
Iterator and ListIterator
Methods
• Iterators allow you to move through a list easily
• Similar to an index variable for an array
Iterators and Loops
• Iterators are often used in while and “for-each” loops
• hasNext returns true if there is a next element
• next returns a reference to the value of the next element

while (iterator.hasNext())
{
String name =
iterator.next();
// Do something with namefor (String name :
} employeeNames)
{
// Do something with name
}
• Where is the iterator in the “for-next” loop?
• It is used ‘behind the scenes’
Adding and Removing with
Iterators
• Adding iterator.add("Juliet");
• A new node is added AFTER the Iterator
• The Iterator is moved past the new node
• Removing
• Removes the object that was returned with the last call to next or
previous
• It can be called only once after next or previous
• You cannot call it immediately after a call to add.
while (iterator.hasNext())
{
String name = iterator.next();
if (condition is true for
name)
{
If you call the remove method improperly, it iterator.remove();
throws an IllegalStateException. }
}
ListDemo.java (1)
• Illustrates adding, removing and printing a list
ListDemo.java (2)
Difference between ArrayList and
LinkedList
ArrayList LinkedList

1) ArrayList internally uses dynamic array to store the LinkedList internally uses doubly linked list to store the
elements. elements.

2) Manipulation with ArrayList is slow because it internally Manipulation with LinkedList is faster than ArrayList because it
uses array. If any element is removed from the array, all the uses doubly linked list so no bit shifting is required in memory.
bits are shifted in memory.

3) ArrayList class can act as a list only because it implements LinkedList class can act as a list and queue both because it
List only. implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

45
List Interface

• List Interface is the subinterface of Collection. It contains methods to


insert and delete elements in index basis.It is a factory of ListIterator
interface.

46
List Interface

Commonly used methods of List Interface:


• public void add(int index,Object element);
• public boolean addAll(int index,Collection c);
• public object get(int Index position);
• public object set(int index,Object element);
• public object remove(int index);
• public ListIterator listIterator();
• public ListIterator listIterator(int i);

47
ListIterator Interface

• ListIterator Interface is used to traverse the element in backward and


forward direction.
Commonly used methods of ListIterator Interface:
• public boolean hasNext();
• public Object next();
• public boolean hasPrevious();
• public Object previous();

48
Example of ListIterator
Interface
import java.util.*;
public class TestCollection8{
public static void main(String args[]){ Output:
element at 2nd position: Vijay
ArrayList<String> al=new ArrayList<String>(); traversing elements in
al.add("Amit"); forward direction...
Amit
al.add("Vijay"); Sachin
al.add("Kumar"); Vijay
al.add(1,"Sachin"); Kumar
traversing elements in
System.out.println("element at 2nd position: "+al.get(2)); backward direction...
Kumar
Vijay
ListIterator<String> itr=al.listIterator(); Sachin
Amit
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());
}
}
} 49
Sorting List elements
• public void sort(List list): is used to sort the elements of List
// Example of Sorting the elements of List that contains
string objects

import java.util.*;
class TestSort1{
public static void main(String args[]){ Output:
Mukesh
ArrayList<String> al=new ArrayList<String>();
Saurav
al.add("Viru");
al.add("Saurav"); Tahir
al.add("Mukesh"); Viru
al.add("Tahir");

Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
50
Sorting List elements that contains Wrapper class
objects

import java.util.*;
class TestSort2{
public static void main(String args[]){

ArrayList al=new ArrayList();


al.add(Integer.valueOf(201)); Output:101
al.add(Integer.valueOf(101)); 201
al.add(230);//internally will be converted into objects as Integer.valueOf(230) 230
Collections.sort(al);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

51
Comparable interface

• Comparable interface is used to order the objects of user-defined


class.

• This interface is found in java.lang package and contains only one


method named compareTo(Object).

• It provide only single sorting sequence i.e. you can sort the elements
on based on single datamember only.For instance it may be either
rollno,name,age or anything else.

52
Comparable interface

Syntax:
• public int compareTo(Object obj): is used to compare the current
object with the specified object.

We can sort the elements of:


• String objects
• Wrapper class objects
• User-defined class objects

53
Comparable interface

• Collections class provides static methods for sorting the elements of


collection.If collection elements are of Set type, we can use TreeSet.
But We cannot sort the elements of List.Collections class provides
methods for sorting the elements of List type elements.
Method of Collections class for sorting:
• public void sort(List list): is used to sort the elements of List.List
elements must be of Comparable type.

54
Sorting List elements that contains user-defined
objects
//Save as Student.java // Save as Simple.java
class Student implements Comparable{ import java.util.*;
int rollno; import java.io.*;
String name;
class TestSort3{
int age; public static void main(String args[]){
Student(int rollno,String name,int age){
this.rollno=rollno; ArrayList al=new ArrayList();
this.name=name; al.add(new Student(101,"Vijay",23));
this.age=age; al.add(new Student(106,"Ajay",27));
} al.add(new Student(105,"Jai",21));
public int compareTo(Object obj){
Collections.sort(al);
Student st=(Student)obj;
Iterator itr=al.iterator();
if(age==st.age) while(itr.hasNext()){
return 0; Student st=(Student)itr.next();
else if(age>st.age) System.out.println(st.rollno+""+st.name+""+st.a
return 1; ge);
else }}}
return -1;
Output:
} } 105 Jai 21
101 Vijay 23
106 Ajay 27 55
Comparator interface

• Comparator interface is used to order the objects of user-defined


class.
• This interface is found in java.util package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element).
• It provides multiple sorting sequence i.e. you can sort the elements
based on any data member. For instance it may be on rollno, name,
age or anything else.

56
Method of Collections class for sorting List
elements

• public void sort(List list,Comparator c): is used to sort the elements


of List by the given comparator.

57
Example of Sorting List that contains user-
defined objects
//Student.java //AgeComparator.java
class Student{ import java.util.*;
int rollno; class AgeComparator implements Comparator{
String name; public int Compare(Object o1,Object o2){
int age; Student s1=(Student)o1;
Student(int rollno,String name,int age){ Student s2=(Student)o2;
this.rollno=rollno; if(s1.age==s2.age) return 0;
this.name=name; else if(s1.age>s2.age) return 1;
this.age=age; else return -1;
} } }
}
//NameComparator.java
import java.util.*;
class NameComparator implements Comparator{
public int Compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

return s1.name.compareTo(s2.name);
}
} 58
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age); } Output:
System.out.println("sorting by age..."); Sorting by Name...
Collections.sort(al,new AgeComparator()); 106 Ajay 27
Iterator itr2=al.iterator(); 105 Jai 21
while(itr2.hasNext()){ 101 Vijay 23
Student st=(Student)itr2.next(); Sorting by age...
System.out.println(st.rollno+" "+st.name+" "+st.age); 105 Jai 21
} } } 101 Vijay 23
106 Ajay 27
59
import java.util.Comparator;
public class Student {
private String studentname;
private int rollno;
private int studentage;
Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
...
//Getter and setter methods same as the above examples
...
/*Comparator for sorting the list by Student Name*/
public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
public int compare(Student s1, Student s2) {
String StudentName1 = s1.getStudentname().toUpperCase();
String StudentName2 = s2.getStudentname().toUpperCase();
return StudentName1.compareTo(StudentName2); //ascending order
//return StudentName2.compareTo(StudentName1); //descending order
}};
/*Comparator for sorting the list by roll no*/
public static Comparator<Student> StuRollno = new Comparator<Student>() {
public int compare(Student s1, Student s2) {
int rollno1 = s1.getRollno();
int rollno2 = s2.getRollno();
return rollno1-rollno2; /*For ascending order*/
//rollno2-rollno1; /*For descending order*/
}};
@Override
public String toString() {
return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
}
} 60
Sorting ArrayList<Object> multiple properties with
Comparator
import java.util.*;
public class Details {

public static void main(String args[]){


ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(101, "Zues", 26));
arraylist.add(new Student(505, "Abey", 24));
arraylist.add(new Student(809, "Vignesh", 32));

/*Sorting based on Student Name*/


System.out.println("Student Name Sorting:");
Collections.sort(arraylist, Student.StuNameComparator);

for(Student str: arraylist){


System.out.println(str);
}

/* Sorting on Rollno property*/


System.out.println("RollNum Sorting:");
Collections.sort(arraylist, Student.StuRollno);
for(Student str: arraylist){
System.out.println(str);
}
}
61
}
Difference between Comparable and
Comparator
• Comparable and Comparator both are interfaces and can be used to sort
collection elements
Comparable Comparator

1) Comparable provides single sorting sequence. In other Comparator provides multiple sorting sequence. In other
words, we can sort the collection on the basis of single element words, we can sort the collection on the basis of multiple
such as id or name or price etc. elements such as id, name and price etc.

2) Comparable affects the original class i.e. actual class is Comparator doesn't affect the original class i.e. actual class is
modified. not modified.

3) Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.

4) Comparable is found in java.lang package. Comparator is found in java.util package.

5) We can sort the list elements of Comparable type by We can sort the list elements of Comparator type by
Collections.sort(List) method. Collections.sort(List,Comparator) method.

62
The Vector Class

• Vector implements a dynamic array. It is similar to ArrayList, but with


two differences:
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections framework.

63
Some Methods of Vector class
• void add(int index, Object element)
• boolean addAll(Collection c)
• boolean addAll(int index, Collection c)
• void addElement(Object obj)
• int capacity()
• void clear()
• Object clone()
• boolean contains(Object elem)
• boolean containsAll(Collection c)
• void copyInto(Object[] anArray)
• Object elementAt(int index)
64
Example of Vector
import java.util.*;

public class VectorExample {


public static void main(String args[]) {
/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);
/* Adding elements to a vector*/
vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");

/* check size and capacityIncrement*/


System.out.println("Size is: "+vec.size());
System.out.println("Default capacity increment is: "+vec.capacity());
vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
/*size and capacityIncrement after two insertions*/
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after increment is: "+vec.capacity());

/*Display Vector elements*/


Enumeration en = vec.elements();
System.out.println("\nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
}
65
}
Similarities between ArrayList and
Vector

• Both Vector and ArrayList use growable array data structure.


• They both are ordered collection classes as they maintain the
elements insertion order.
• Vector & ArrayList both allows duplicate and null values.
• They both grows and shrinks automatically when overflow and
deletion happens.

66
Difference between ArrayList and
Vector
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current array size if Vector increments 100% means doubles the array size if
number of element exceeds from its capacity. total number of element exceeds than its capacity.

3) ArrayList is not a legacy class Vector is a legacy class.

Vector is slow because it is synchronized i.e. in


multithreading environment, it will hold the other threads
4) ArrayList is fast because it is non-synchronized.
in runnable or non-runnable state until current thread
releases the lock of object.

5) ArrayList uses Iterator interface to traverse the Vector uses Enumeration interface to traverse the
elements. elements. But it can use Iterator also.

67
Difference between ArrayList and Vector
Example of Java ArrayList Example of Java Vector
//simple example where we are using ArrayList to store and
traverse the elements.
//simple example of java Vector class that uses Enumeration
interface.
import java.util.*; import java.util.*;
class TestArrayList21{ class TestVector1{
public static void main(String args[]){ public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
List<String> al=new ArrayList<String>();//creating arraylist v.add("umesh");//method of Collection
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
v.addElement("irfan");//method of Vector
al.add("James"); v.addElement("kumar");
al.add("Andy"); //traversing elements using Enumeration
//traversing elements using Iterator Enumeration e=v.elements();
Iterator itr=al.iterator(); while(e.hasMoreElements()){
while(itr.hasNext()){ System.out.println(e.nextElement());
System.out.println(itr.next()); } } }
} }}

Output:
Sonoo Output:
Michael umesh
James irfan
Andy kumar

68
When to use ArrayList and when to use
vector?

• Synchronized operations consumes more time compared to non-


synchronized ones so if there is no need for thread safe operation,
ArrayList is a better choice as performance will be improved because
of the concurrent processes.

69
Properties class in Java

• The properties object contains key and value pair both as a string. It is
the subclass of Hashtable.
• It can be used to get property value based on the property key.
• The Properties class provides methods to get data from properties file
and store data into properties file.
• it can be used to get properties of system.

70
Advantage of properties file

• Easy Maintenance: If any information is changed from the properties


file, you don't need to recompile the java class. It is mainly used to
contain variable information i.e. to be changed.

71
Methods of Properties class
Method Description
public void load(Reader r) loads data from the Reader object.

public void load(InputStream is) loads data from the InputStream object

public String getProperty(String key) returns value based on the key.

public void setProperty(String key,String value) sets the property in the properties object.

public void store(Writer w, String comment) writers the properties in the writer object.

public void store(OutputStream os, String comment) writes the properties in the OutputStream object.

writers the properties in the writer object for generating


storeToXML(OutputStream os, String comment)
xml document.

public void storeToXML(Writer w, String comment, String writers the properties in the writer object for generating
encoding) xml document with specified encoding.

72
Example of Properties class to get
information from properties file
To get information from the properties file, create the properties file first.
db.properties
user=system
password=oracle
Now, lets create the java class to read the data from the properties file.
//save as Test.java
import java.util.*;
import java.io.*; Output:
public class Test {
public static void main(String[] args)throws Exception{ system
FileReader reader=new FileReader("db.properties"); oracle
Properties p=new Properties();
p.load(reader); System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}

Now if you change the value of the properties file, you don't need to compile the java
class again. That means no maintenance problem.
73
Example of Properties class to get all the system
properties
• By System.getProperties() method we can get all the properties of system. Let's
create the class that gets information from the system properties.

import java.util.*; Output:


import java.io.*; java.runtime.name = Java(TM) SE
Runtime Environment
public class Test {
sun.boot.library.path = C:\Users\
public static void main(String[] args)throws Exception{ JOYSANA\AppData\Local\Genuitec\
Properties p=System.getProperties(); Common\binary\
Set set=p.entrySet(); com.sun.java.jdk.win32.x86_1.6.0.013
Iterator itr=set.iterator(); \jre\bin
while(itr.hasNext()){ java.vm.version = 11.3-b02
java.vm.vendor = Sun Microsystems
Map.Entry entry=(Map.Entry)itr.next();
Inc.
System.out.println(entry.getKey()+" = "+entry.getValue()); java.vendor.url =
} } } http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM)
Client VM
file.encoding.pkg = sun.io
sun.java.launcher = SUN_STANDARD
...........

74
Example of Properties class to create properties file

import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{

Properties p=new Properties();


p.setProperty("name","Dibya Jyoti Sana");
p.setProperty("email","[email protected]");

p.store(new FileWriter("info.properties"),"Java for Complete Beginners");

}
}

info.properties
--------------------
#Java for Complete Beginners
#date time
[email protected]
name=Dibya Jyoti Sana
75
Summary
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• -----------------------------------------------------------
• LinkedList class can contain duplicate elements.
• LinkedList class maintains insertion order.
• LinkedList class is non synchronized.
• -------------------------------------------
• HashSet maintain no order
• HashSet Contains unique elements only.
• HashSet is not synchronized
• HashSet contains only values not key

76
Summary
• LinkedHashSet maintains the insertion order
• LinkedHashSet Contains unique elements
• ------------------------------------------------------
• TreeSet Contains unique elements
• TreeSet sorts the elements in ascending order
• --------------------------------------------------------
• priority queue are ordered according to their natural ordering
• ------------------------------------------------------------
• HashMap contains values based on the key
• It contains only unique elements
• It maintains no order.
• HashMap contains entry(key and value).
• not synchronized
77
Summary
• LinkedHashMap contains only unique elements
• LinkedHashMap contains values based on the key
• It contains only unique elements.
• It maintains insertion order
• --------------------------------------------------------------------------
• TreeMap contains only unique elements
• Elements will be sorted in ascending key order
• TreeMap contains values based on the key
• -----------------------------------------------------------------------------
• Hashtable is an array of list. Each list is known as a bucket.The position of bucket is identified by calling the
hashcode() method.
• It contains only unique elements.
• It is synchronized.

78
Sets
• A set is an unordered collection
• It does not support duplicate elements

• The collection does not keep track of the order in which elements have
been added
• Therefore, it can carry out its operations more efficiently than an ordered collection

The HashSet and TreeSet classes both


implement the Set interface.
Sets

• HashSet: Stores data in a Hash Table


• TreeSet: Stores data in a Binary Tree
• Both implementations arrange the set
elements so that finding, adding, and
removing elements is efficient

Set implementations arrange the elements


so that they can locate them quickly
Hash Table Concept
• Set elements are grouped into smaller
collections of elements that share the
same characteristic
• It is usually based on the result of a
mathematical calculation on the contents
that results in an integer value 100
• In order to be stored in a hash table,
elements must have a method to compute
their integer values
101

102
hashCode

• The method is called hashCode


• If multiple elements have the same hash code, they are stored in a Linked list

• The elements must also have an equals method for checking whether an
element equals another like:
• String, Integer, Point, Rectangle, Color, and all collection classes

Set<String> names = new


HashSet<String>();
Tree Concept
• Set elements are kept in sorted order
• Nodes are not arranged in a linear sequence
but in a tree shape

• In order to use a TreeSet, it must be possible to compare the


elements and determine which one is “larger”
TreeSet

• Use TreeSet for classes that implement the


Comparable interface
• String and Integer, for example
• The nodes are arranged in a ‘tree’ fashion so that each ‘parent’
node has up to two child nodes.
• The node to the left always has a ‘smaller’ value
• The node to the right always has a ‘larger’ value

Set<String> names = new


TreeSet<String>();
Iterators and Sets
• Iterators are also used when processing sets
• hasNext returns true if there is a next element
• next returns a reference to the value of the next element
• add via the iterator is not supported for TreeSet and HashSet

Iterator<String> iter =
names.iterator();
while (iter.hasNext())
for (String name : names)
{
{
String name = iter.next();
// Do something with name
// Do something with name
}
}

• Note that the elements are not visited in the order in which you inserted them.
• They are visited in the order in which the set keeps them:
• Seemingly random order for a HashSet
• Sorted order for a TreeSet
Working With Sets (1)
Working With Sets (2)
SpellCheck.java (1)
SpellCheck.java (2)
Maps
• A map allows you to associate elements from a key set
with elements from a value collection.
• The HashMap and TreeMap classes both implement the Map
interface.

• Use a map to look up objects by using a key.


Maps
Key Value Key Value

Map<String, Color> favoriteColors = new HashMap<String,


Color>();
Working with Maps (Table 5)
Key Value Pairs in Maps
• Each key is associated with a value

Map<String, Color> favoriteColors = new HashMap<String,


Color>();
favoriteColors.put("Juliet", Color.RED);
favoriteColors.put(“Romeo", Color.GREEN);
Color julietsFavoriteColor = favoriteColors.get("Juliet");
favoriteColors.remove("Juliet");
Iterating through Maps
• To iterate through the map, use a keySet to get the list of
keys:
Set<String> keySet = m.keySet();
for (String key : keySet)
{
Color value = m.get(key);
System.out.println(key + "->" + value);
}

To find all values in a map,


iterate through the key set
and find the values that
correspond to the keys.
MapDemo.java
Steps to Choosing a Collection
1) Determine how you access values
• Values are accessed by an integer position. Use an ArrayList
• Go to Step 2, then stop
• Values are accessed by a key that is not a part of the object
• Use a Map.
• It doesn’t matter. Values are always accessed “in bulk”, by traversing the collection
and doing something with each value
2) Determine the element types or key/value types
• For a List or Set, a single type
• For a Map, the key type and the value type
Steps to Choosing a Collection
3) Determine whether element or key order matters
• Elements or keys must be sorted
• Use a TreeSet or TreeMap. Go to Step 6
• Elements must be in the same order in which they were inserted
• Your choice is now narrowed down to a LinkedList or an ArrayList
• It doesn’t matter
• If you chose a map in Step 1, use a HashMap and go to Step 5

4) For a collection, determine which operations must be fast


• Finding elements must be fast
• Use a HashSet and go to Step 5

• Adding and removing elements at the beginning or the middle must be fast
• Use a LinkedList

• You only insert at the end, or you collect so few elements that you aren’t concerned about
speed
• Use an ArrayList.
Steps to Choosing a Collection

5) For hash sets and maps, decide if you need to implement the
equals and hashCode methods
• If your elements do not support them, you must implement them yourself.
6) If you use a tree, decide whether to supply a comparator
• If your element class does not provide it, implement the Comparable
interface for your element class
Special Topic: Hash Functions
• Hashing can be used to find elements in a set data structure quickly,
without making a linear search through all elements.
• A hashCode method computes and returns an integer value: the hash
code.
• Should be likely to yield different hash codes
• Because hashing is so important, the Object class has a hashCode method that
computes the hash code of any object x.

int h =
x.hashCode();
Computing Hash Codes
• To put objects of a given class into a HashSet or use the
objects as keys in a HashMap, the class should override the
default hashCode method.
• A good hashCode method should work such that different
objects are likely to have different hash codes.
• It should also be efficient
• A simple example for a String might be:

int h = 0;
for (int i = 0; i < s.length(); i+
+)
{
h = h + s.charAt(i);
}
Computing Hash Codes

• But Strings that are permutations of another (such as "eat" and "tea")
would all have the same hash code
• Better:
• From the Java Library!
final int HASH_MULTIPLIER = 31;
int h = 0;
for (int i = 0; i < s.length(); i++)
{
h = HASH_MULTIPLIER * h +
s.charAt(i);
}
Sample Strings and HashCodes
• The String class implements a good example of a hashCode
method
• It is possible for two or more distinct objects to have the same
hash code: This is called a collision
• A hashCode function should minimizes collisions
Computing Object Hash Codes
• You should have a good hashCode method for your own objects to store them
efficiently
• Override hashCode methods in your own classes by combining the hash codes
for the instance variables
public int hashCode()
{
int h1 = name.hashCode();
int h2 = new
Double(area).hashCode();
. . .
• Then combine the hash codes using a prime-number hash multiplier:
final int HASH_MULTIPLIER = 29;
int h = HASH_MULTIPLIER * h1 + h2;
return h;
}
hashCode and equals methods
• hashCode methods should be compatible with equals methods
• If two objects are equal, their hashCodes should match
• a hashCode method should use all instance variables
• The hashCode method of the Object class uses the memory location of the object,
not the contents
hashCode and equals methods

• Do not mix Object class hashCode or equals methods with your own:
• Use an existing class such as String. Its hashCode and equals methods have already
been implemented to work correctly.
• Implement both hashCode and equals.
• Derive the hash code from the instance variables that the equals method compares, so that equal objects
have the same hash code

• Implement neither hashCode nor equals. Then only identical objects are considered to
be equal
Difference between HashMap and
Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.
HashMap Hashtable

1) HashMap is non synchronized. It is not-thread safe and


Hashtable is synchronized. It is thread-safe and can be
can't be shared between many threads without proper
shared with many threads.
synchronization code.

2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.


4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by calling


Hashtable is internally synchronized and can't be
this code
unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

6) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.


7) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

106
Stacks, Queues and Priority Queues
• Queues and Stacks are specialized lists
• Only allow adding and removing from the ends

Insert At Remove At Operation


Stack Start(top) Start(top) List in, first out (LIFO)
Queue End (tail) Start (head) First in, first out (FIFO)
Priority Queue By Priority Highest Prioritized list of tasks
Priority
(Lowest #)
Stacks, Queues and Priority
Queues
• Stacks are used for undo features
(most recent first)

• Queues are like lines at the bank


or store

• Priority Queues remove lowest


number first
Working with Stacks
Stack Example
• The Java library provides a Stack class that implements the abstract
stack type’s push and pop operations.
• The Stack is not technically part of the Collections framework, but uses generic
type parameters

Stack<String> s = new Stack<String>();


s.push("A");
s.push("B");
s.push("C");
// The following loop prints C, B, and
A
while (s.size() > 0)
The stack class {
provides a size method System.out.println(s.pop());
}
Queues and Priority Queues
Priority Queues
• A priority Queue collects elements, each of which has a
priority
• Example: a collection of work requests, some of which may
be more urgent than others
• It is NOT a FIFO Queue

PriorityQueue<WorkOrder> q = new
PriorityQueue<WorkOrder>();
q.add(new WorkOrder(3, "Shampoo carpets"));
q.add(new WorkOrder(1, "Fix broken sink"));
q.add(new WorkOrder(2, "Order cleaning supplies"));
• Lowest value priority (1) will be removed first

WorkOrder next = q.remove(); // removes “Fix broken


sink”
Stack and Queue Applications
• Balancing Parenthesis
• One of previous Section showed how to balance parenthesis by adding 1 for each
left ( and subtracting for each right )

• A stack can be used to keep track of ‘depth’:


When you see an opening parenthesis, push it on the stack.
When you see a closing parenthesis, pop the stack.
If the opening and closing parentheses don’t match
The parentheses are unbalanced. Exit.
If at the end the stack is empty
The parentheses are balanced.
Else
The parentheses are not balanced.
Using a Stack (Example)
• Here is a walkthrough of the sample expression
• We will use the mathematical version (three types of parenthesis)
Reverse Polish Expressions
• The first handheld calculator used a notation that was easily implemented with a stack:
Reverse Polish

• No parenthesis required if you…

• Input both operands first, then the operator:

Algebra Reverse Polish


(3 + 4) x 5 3 4 + 5 x
(3 + 4) x (5 + 6) 3 4 + 5 6 + x
Reverse Polish Expressions

If you read a number


Push it on the stack.
Else if you read an operand
Pop two values off the stack.
Combine the values with the operand.
Push the result back onto the stack.
Else if there is no more input
Pop and display the result.
Reverse Polish Calculator
• Walkthrough with 3 4 5 + x
Calculator.java (1)
Calculator.java (2)
Evaluating Algebraic Expressions
• Can be done with two stacks:
1) Numbers
2) Operators
• First Example: 3 + 4
Expression Example 2
• Second Example: 3 x 4 + 5

• Must use precedence (multiply before adding)


Precedence and Expressions (1)
• Third Example: 3 + 4 x 5

• Keep operators on the stack until they are ready to be


evaluated
Precedence and Expressions (2)
• Third Example: 3 + 4 x 5

• Evaluate top 2 numbers with top operator


• Store result on top of stack
• Evaluate until operator stack is empty
Expressions with Parenthesis (1)
• Fourth Example: 3 x ( 4 + 5 )

• If (, don’t evaluate. If ), evaluate


Expressions with Parenthesis (2)
• Fourth Example: 3 x ( 4 + 5 )

• Don’t put ) on stack – evaluate now


• Ignore (
Precedence Algorithm
If you read a number
Push it on the number stack.
Else if you read a (
Push it on the operator stack.
Else if you read an operator op
While the top of the stack has a higher precedence than op
Evaluate the top.
Push op on the operator stack.
Evaluate the Top:
Else if you read a )
While the top of the stack is not a ( Pop two numbers off the
Evaluate the top. number stack.
Pop the ). Pop an operator off the
Else if there is no more input operator stack.
While the operator stack is not empty Combine the numbers
Evaluate the top. with that operator.
Push the result on the
number stack.
Backtracking (1)
• Uses a stack to solve a maze
• Stack current location, arrow for
each possible path
1. We pop off the topmost one,
traveling north from (3, 4).
Following this path leads to
position (1, 4).
2. We now push two choices on
the stack, going west or east.
Backtracking (2)
3. Pop off (1, 4) east. It is a dead
end.

4. Pop off (1, 4) west. It is a dead


end.

5. Now we pop off the path from


(3, 4) going east. That too is a
dead end.
This leaves us with (3, 4) south and
(3, 4) west to try
Backtracking (3)
6. Next is the path from (3, 4) going
south. At (5, 4), it comes to an
intersection. Both choices are
pushed on the stack.
7. (5, 4) south is a dead end.
8. (5, 4) west is a dead end.
9. Finally, the path from (3, 4) going
west leads to an exit
Maze Solving Pseudocode

Push all paths from the point on which you are standing on a stack.
While the stack is not empty
Pop a path from the stack.
Follow the path until you reach an exit, intersection, or dead
end.
If you found an exit
Congratulations!
Else if you found an intersection
Push all paths meeting at the intersection, except the current one, onto
the stack.
The HashMap Class
• The HashMap class is one of the most valuable tools exported by the java.util package
and comes up in a surprising number of applications (including FacePamphlet).

• The HashMap class implements the abstract idea of a map, which is an associative
relationship between keys and values. A key is an object that never appears more than
once in a map and can therefore be used to identify a value, which is the object associated
with a particular key.

• Although the HashMap class exports other methods as well, the essential operations on a
HashMap are the ones listed in the following table:
new HashMap( ) Creates a new HashMap object that is initially empty.
map.put(key, value) Sets the association for key in the map to value.
map.get(key) Returns the value associated with key, or null if none.

HashMap<String,Integer> indicates a HashMap that uses strings as keys to obtain


integer values.
A Simple HashMap Application
• Suppose that you want to write a program that displays the name of a state given its two-
letter postal abbreviation.
• This program is an ideal application for the HashMap class because what you need is a
map between two-letter codes and state names. Each two-letter code uniquely identifies
a particular state and therefore serves as a key for the HashMap; the state names are the
corresponding values.

• To implement this program in Java, you need to perform the following steps, which are
illustrated on the following slide:
1. Create a HashMap containing all 50 key/value pairs.
2. Read in the two-letter abbreviation to translate.
3. Call get on the HashMap to find the state name.
4. Print out the name of the state.
The PostalLookup Application
public void run() {
HashMap<String,String> stateMap = new HashMap<String,String>();
private void initStateMap(HashMap<String,String> map) {
initStateMap(stateMap);
map.put("AL", "Alabama");
while (true) {
map.put("AK", "Alaska");
String code = readLine("Enter two-letter state abbreviation: ");
map.put("AZ", "Arizona");
if (code.length()
... == 0) break;
String state = stateMap.get(code);
map.put("FL", "Florida");
if (state == null) {
map.put("GA", "Georgia");
println(code + " is not a known state abbreviation");
map.put("HI", "Hawaii");
} else { . . .
println(code + " is " + state);
map.put("WI", "Wisconsin"); state code stateMap
}
map.put("WY", "Wyoming"); map
} null
Hawaii
Wisconsin VE
WI
HI
}
}

PostalLookup AL=Alabama
Enter two-letter state abbreviation: HI AK=Alaska
AZ=Arizona
HI is Hawaii ...
Enter two-letter state abbreviation: WI FL=Florida
WI is Wisconsin GA=Georgia
Enter two-letter state abbreviation: VE HI=Hawaii
VE is not a known state abbreviation ...
Enter two-letter state abbreviation: WI=Wisconsin
WY=Wyoming
skip simulation

You might also like