Lecture 28, 29, 30 Collection Framework in Java
Lecture 28, 29, 30 Collection Framework in Java
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>
SortedSet
<interface>
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>
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>
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.
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
9 public boolean containsAll(Collection c) is used to search the specified collection in this 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
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");
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
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;
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[]){
al.removeAll(al2);
al.retainAll(al2);
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
• 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
• Removal of a node
• Find the element to remove
• Remap neighbor’s references
• Inefficient Operations
• Random access
Each instance variable is declared just
like other variables we have used.
LinkedList: Important
Methods
Generic Linked Lists
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()
iterator.next();
iterator.add(“J”)
;
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
46
List Interface
47
ListIterator Interface
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[]){
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
51
Comparable interface
• 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.
53
Comparable interface
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
56
Method of Collections class for sorting List
elements
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 {
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.
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
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.*;
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.
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?
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
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 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.
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.
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{
}
}
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
102
hashCode
• 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
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.
• 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
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.
106
Stacks, Queues and Priority Queues
• Queues and Stacks are specialized lists
• Only allow adding and removing from the ends
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
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.
• 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