Collections With Exercise
Collections With Exercise
© Amir Kirsh
Collections Overview
2
Collections
http://java.sun.com/javase/6/docs/technotes/guides/collections/ref
erence.html
5
Java Collection Framework
Iterator and Collection interface
9
ArrayList
10
String s = (String) itr.next();
System.out.println(s);
Example ArrayList
1st Example:
static public void main(String[] args) {
ArrayList argsList = new ArrayList();
for(String str : args) {
argsList.add(str);
}
if(argsList.contains("Koko") {
System.out.println("We have Koko");
}
String first = (String)argsList.get(0);
System.out.println("First: " + first);
}
12
Example ArrayList
13
HashMap
HashMap is a non-synchronized key-value Hashtable
Example 1:
HashMap<String, Person> id2Person;
...
Person p = id2Person.get("021212121");
if(p != null) {
System.out.println("found: " + p);
}
14
HashMap
Example 2:
HashMap<String, Integer> frequency(String[] names) {
HashMap<String, Integer> frequency =
new HashMap<String, Integer>();
for(String name : names) {
Integer currentCount = frequency.get(name);
if(currentCount == null) {
currentCount = 0; // auto-boxing
}
frequency.put(name, ++currentCount);
}
return frequency;
}
15
HashMap
Example 2 (cont’):
public static void main(String[] args) {
System.out.println( (
(
frequency(new String[]{
"Momo", "Momo", "Koko", "Noa", "Momo", "Koko"
) )
}).toString());
}
HashMap has a nice toString!
Print out of this main is:
{Koko=2, Noa=1, Momo=3}
HashMap doesn’t
guarantee any order!
16
HashMap
Example:
Parameter MUST be Object
public class Person {
public String name; (and NOT Person!)
boolean equals(Object o) {
return (o instanceof Person &&
((Person)o).name.equals(name));
}
public int hashCode() {
return name.hashCode();
}
}
17
Hash Map Example Traversal
19
20
Exercise 1
21
Exercise 2
Example
For the following input: Hey how are you?
we expect the following chart:
A #
E ##
H ##
O ##
R #
Y ##
U #
W #
22