Professional Documents
Culture Documents
Content
The bouncing-ball system
The tech-support system
HashMap
HashSet
Learning Objectives
Students should be able
to recognize and use Java constants
to use class Random
to use simple Java Collection classes:
ArrayList (as an example of List),
HashMap (as an example of Map),
HashSet (as an example of Set)
Chapter 5: bouncing-balls
y-axis
groundPosition
Object diagram
Section 5.13
A class variable
ie static
Instance variables
Constant
private static final int GRAVITY = 3;
final: constant
type
All in pixels
ballDegradation is 2 and
is loss of speed at
bounce
bounce!
(int) unnecessary
7
A common
iteration pattern.
}
else {
do something more
}
}
(c) Barnes & Kolling
else {
String response =
responder.generateResponse(input);
System.out.println(response);
}
}
Later Strings startsWith() will be
replaced by HashSetss contains().
(c) Barnes & Kolling
10
charAt(int pos)
indexOf(String target)
contains(String target)
endsWith(String target)
toUpperCase()
trim()
split(String regex)
11
Responder
private
ArrayList<String> defaultResponses;
(Actually an array
could be used here.)
12
Random randomGenerator;
public Responder()
{ ...
randomGenerator = new Random();
}
private String pickDefaultResponse()
{
int index =
randomGenerator.nextInt( defaultResponses.size() );
return defaultResponses.get(index);
}
0
(c) Barnes & Kolling
(size 1)
13
14
Using Sets
import java.util.HashSet;
...
HashSet<String> mySet = new HashSet<String>();
mySet.add("one");
mySet.add("two");
mySet.add("three");
No change to mySet
"two" already present.
mySet.add("two");
Maps
"Charles Nguyen"
"Lisa Jones"
"William H. Smith"
17
Using a map
HashMap <String, String> phoneBook =
new HashMap<String, String>();
phoneBook.put("Charles Nguyen", "(531) 9392 4587");
phoneBook.put("Lisa Jones", "(402) 4536 4674");
phoneBook.put("William H. Smith", "(998) 5488 0123");
//later:
String phoneNumber = phoneBook.get("Lisa Jones");
System.out.println(phoneNumber);
18
List
ArrayList, LinkedList
Set
HashSet, TreeSet
Map
HashMap,
19
Hashed collections
hashCode()
Hashing
Elements are scattered around an array,
key
array index
K1,V1
K6,V6
K4,V4
K2,V2
simplified
21
22
return pickDefaultResponse();
}
ArrayLists get vs
HashMaps get
(c) Barnes & Kolling
23
Exercises:
Modify Responder so it cannot randomly choose the same response as
last time.
What happens when you add (put) to a Map, another entry with the same
key?
How do you print out all the keys of a Map?
Set has a method contains() that depends on the element class having a
Reading:
Barnes & Kolling 5.1 - 5.9
24