GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
CẤU TRÚC DỮ LIỆU
DATA STRUCTURES
[214331]
Iterator - Comparable - Comparator
1
/XX
12/3/15
Nguyễn Xuân Vinh
2
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
GV: NGUYỄN XUÂN VINH
Java Collection Architecture
GV: NGUYỄN XUÂN VINH
The Differences!!!
How to browse element?
Elements of List are indexed.
List
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
Linked List
int value = list[0];
Elements of LinkedList, Sets and Maps can't be accessed
MÔN: CẤU TRÚC DỮ LIỆU
by index
How to remove element?
"the"
Set
"from"
/XX
12/3/15
Map
3
"to"
"we"
GV: NGUYỄN XUÂN VINH
Examining sets and maps
elements of Java Sets and Maps can't be accessed by index
must use a "foreach" loop:
Set<Integer> scores = new HashSet<Integer>();
for (int score : scores) {
System.out.println("The score is " + score);
MÔN: CẤU TRÚC DỮ LIỆU
}
Problem: foreach is read-only; cannot modify set while looping
for (int score : scores) {
if (score < 60) {
// throws a ConcurrentModificationException
scores.remove(score);
}
4
/XX
12/3/15
}
iterator: An object that allows a client to traverse the elements of any collection, regardless of its implementation.
Remembers a position within a collection, and allows you to:
get the element at that position
advance to the next position
(possibly) remove or change the element at that position
MÔN: CẤU TRÚC DỮ LIỆU
GV: NGUYỄN XUÂN VINH
Iterators (11.1)
index
0
1
2
3
4
5
6
7
8
9
value
3
8
9
7
5
12
0
0
0
0
size
6
/XX
12/3/15
list
Benefit: A common way to examine any collection's elements.
5
iterator
set
"to"
"we"
"from"
current element:
current index:
"the"
2
9
iterator
current element:
next element: "the"
"from"
GV: NGUYỄN XUÂN VINH
Iterator methods
hasNext()
returns true if there are more elements to examine
next()
returns the next element from the collection (throws a NoSuchElementException if there are
none left to examine)
6
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
remove()
removes from the collection the last value returned by next() (throws IllegalStateException
if you have not called next() yet)
Iterator interface in java.util
every collection has an iterator() method that returns an iterator over its elements
Set<String> set = new HashSet<String>();
...
Iterator<String> itr = set.iterator();
GV: NGUYỄN XUÂN VINH
Iterator example
Set<Integer> scores = new HashSet<Integer>();
scores.add(38);
scores.add(94);
scores.add(87);
scores.add(43);
scores.add(62);
MÔN: CẤU TRÚC DỮ LIỆU
...
Iterator<Integer> itr = scores.iterator();
while (itr.hasNext()) {
int score = itr.next();
System.out.println("The score is " + score);
// eliminate any failing grades
if (score < 60) {
itr.remove();
12/3/15
System.out.println(scores);
7
}
/XX
}
// [62, 94, 87]
GV: NGUYỄN XUÂN VINH
Iterator example 2
Map<String, Integer> scores = new HashMap<String, Integer>();
scores.put("Kim", 38);
scores.put("Lisa", 94);
scores.put("Ryan", 87);
scores.put("Morgan", 43);
scores.put("Marisa", 62);
MÔN: CẤU TRÚC DỮ LIỆU
...
Iterator<String> itr = scores.keySet().iterator();
while (itr.hasNext()) {
String name = itr.next();
int score = scores.get(name);
System.out.println(name + " got " + score);
// eliminate any failing students
if (score < 60) {
8
/XX
12/3/15
itr.remove(); // removes name and score
}
}
System.out.println(scores);// {Marisa=62, Lisa=94, Ryan=87}
GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
12/3/15
/XX
9
Exercise
Modify the Book Search program from last lecture to eliminate any words that are plural or all-uppercase from the
collection.
GV: NGUYỄN XUÂN VINH
Set/Map and ordering
Some types have a notion of a natural ordering .
TreeSet/Map store values sorted by their natural ordering.
Set<Integer> scores = new HashSet<Integer>();
scores.add(38);
scores.add(94);
MÔN: CẤU TRÚC DỮ LIỆU
scores.add(87);
scores.add(43);
// unpredictable order
scores.add(62);
System.out.println(scores);
// [62, 94, 43, 87, 38]
Set<Integer> scores = new TreeSet<Integer>();
scores.add(38);
scores.add(94);
12/3/15
System.out.println(scores);
10
scores.add(43);
/XX
scores.add(87);
// sorted natural order
scores.add(62);
// [38, 43, 62, 87, 94]
GV: NGUYỄN XUÂN VINH
Ordering our own types
We cannot make a TreeSet or TreeMap of any arbitrary type, because Java doesn't know how to order the
elements.
The program compiles but crashes when we run it.
MÔN: CẤU TRÚC DỮ LIỆU
Set<HtmlTag> tags = new TreeSet<HtmlTag>();
tags.add(new HtmlTag("body", true));
tags.add(new HtmlTag("b", false));
...
Exception in thread "main" java.lang.ClassCastException
at java.util.TreeMap.put(TreeMap.java:542)
11
/XX
12/3/15
at java.util.TreeSet.add(TreeSet.java:238)
at MyProgram.main(MyProgram.java:24)
GV: NGUYỄN XUÂN VINH
Comparable (10.2)
public interface Comparable<E> {
public int compareTo(E other);
}
12
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
A class can implement the Comparable interface to define a natural ordering function for its objects.
A call of a.compareTo(b) should return:
a value < 0
if a comes "before" b in the ordering,
a value > 0
if a comes "after" b in the ordering,
or
if a and b are considered "equal" in the ordering.
0
GV: NGUYỄN XUÂN VINH
Comparable example
public class Point implements Comparable<Point> {
private int x;
private int y;
...
// sort by x and break ties by y
public int compareTo(Point other) {
MÔN: CẤU TRÚC DỮ LIỆU
if (x < other.x) {
return -1;
} else if (x > other.x) {
return 1;
} else if (y < other.y) {
return -1;
// same x, smaller y
} else if (y > other.y) {
return 1;
// same x, larger y
} else {
12/3/15
return 0;
}
13
/XX
}
}
// same x and same y
GV: NGUYỄN XUÂN VINH
compareTo tricks
subtraction trick - Subtracting related numeric values produces the right result for what you want compareTo to
return:
// sort by x and break ties by y
public int compareTo(Point other) {
if (x != other.x) {
return x - other.x;
// different x
14
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
} else {
return y - other.y;
// same x; compare y
}
}
The idea:
if x
if x
if x
> other.x,
then x - other.x > 0
< other.x,
then x - other.x < 0
== other.x,
then x - other.x == 0
GV: NGUYỄN XUÂN VINH
compareTo tricks 2
delegation trick - If your object's fields are comparable (such as strings), use their compareTo results to help you:
// sort by employee name, e.g. "Jim" < "Susan"
public int compareTo(Employee other) {
return name.compareTo(other.getName());
MÔN: CẤU TRÚC DỮ LIỆU
}
toString trick - If your object's toString representation is related to the ordering, use that to help you:
// sort by date, e.g. "09/19" > "04/01"
public int compareTo(Date other) {
return toString().compareTo(other.toString());
15
/XX
12/3/15
}
GV: NGUYỄN XUÂN VINH
Comparable and sorting
The Arrays and Collections classes in java.util have a static method sort that sorts the elements of
an array/list
Point[] points = new Point[3];
points[0] = new Point(7, 6);
points[1] = new Point(10, 2)
points[2] = new Point(7, -1);
MÔN: CẤU TRÚC DỮ LIỆU
points[3] = new Point(3, 11);
Arrays.sort(points);
System.out.println(Arrays.toString(points));
// (3, 11), (7, -1), (7, 6), (10, 2)
List<Point> points = new ArrayList<Point>();
points.add(new Point(7, 6));
...
16
/XX
12/3/15
Collections.sort(points);
System.out.println(points);
// (3, 11), (7, -1), (7, 6), (10, 2)
GV: NGUYỄN XUÂN VINH
Arrays class
Method name
Description
asList(value1, ..., valueN)
returns a List containing the given values as its elements
binarySearch(array, value)
returns the index of the given value in a sorted array (< 0 if not
17
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
found)
copyOf(array)
returns a new array with same elements
equals(array1, array2)
returns true if the two arrays contain the same elements in the
same order
fill(array, value)
sets every element to have given value
sort(array)
arranges elements into ascending order
toString(array)
returns a string representing the array, such as "[10, 30, 17]"
GV: NGUYỄN XUÂN VINH
Collections class
Method name
binarySearch(list, value)
Description
returns the index of the given value in a sorted list (< 0 if not
18
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
found)
copy(listTo, listFrom)
copies listFrom's elements to listTo
emptyList(), emptyMap(),
returns a read-only collection of the given type that has no
emptySet()
elements
fill(list, value)
sets every element in the list to have the given value
max(collection), min(collection)
returns largest/smallest element
replaceAll(list, old, new)
replaces an element value with another
reverse(list)
reverses the order of a list's elements
shuffle(list)
arranges elements into a random order
sort(list)
arranges elements into ascending order
GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
12/3/15
/XX
19
Comparable basics
Ordering is done through the compareTo() method.
20
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
GV: NGUYỄN XUÂN VINH
System-Defined Comparable classes
GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
12/3/15
/XX
21
Understanding Comparable
public int compareTo(Object obj)
Elements must be mutually comparable:
You can only compare like elements.
Or ClassCastException will be thrown.
In most cases, the two objects must be of the same type (or a subtype)
GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
12/3/15
/XX
22
Understanding Comparable
The return value states the relative position to the natural ordering:
compareTo() method can return one of three values:
Negative number: current object > object compared to.
Positive number: current object < object compared to.
Zero: two objects are equal.
GV: NGUYỄN XUÂN VINH
Understanding Comparable
The natural ordering should be consistent with equals():
Two elements are equal (equals()): compareTo() should return zero.
Your class implements Comparable and inconsistent with equals(): won't work properly within a SortedSet or
23
/XX
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
SortedMap.
GV: NGUYỄN XUÂN VINH
MÔN: CẤU TRÚC DỮ LIỆU
12/3/15
/XX
24
Understanding Comparable
Never call the method directly:
Collections Framework call the compareTo() method for you when necessary.
Not your responsibility to call the method.
25
/XX
Comparator
12/3/15
MÔN: CẤU TRÚC DỮ LIỆU
GV: NGUYỄN XUÂN VINH