Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 18

Menu

• Maps
• Iteration

• Assignment 1 Model Solutions


• friends.add(friends.size() – 1, value)
• friends.add(friends.size(), value)

1
Maps
• Collection of data, but not of single values:
• Map = set of pairs of keys to values
• Constrained access: get values via keys.
• Lots of implementations, most common is HashMap.
put(“Lady Greystoke”, Kathleen Kirkham)
get(“Jane Porter”)
put(“Lady Greystoke”, Anne)
“Jane Porter” ⇒ Enid Markey

“Prof. Porter” ⇒ Thomas Jefferson

“Lady Greystoke” ⇒ Kathleen Kirkham

“Tarzan” ⇒ Elmo Lincoln


No
ordering of
“Lord Greystoke” ⇒ True Boardman
keys
Tarzan of the Apes 1918

2
Maps
• When declaring and constructing, must specify two types:
• Type of the key, and type of the value
private Map<String, String> movieCast; // Could be say <String,
Integer>
:
movieCast = new HashMap<String, String>();

• Central operations:
• get(key), ⇒ the value associated with key
• put(key, value), ⇒ sets value to be associated with key
(and returns the old value, if any)
• remove(key), ⇒ removes key and associated value
(and returns the old value, if any)
• containsKey(key),
• size()
• entrySet ⇒ a Set of Map.Entry’s that you can iterate along.

3
Example: movieCast
private Map<String, String> movieCast;
:
public void lookup(){
      String name = askName(“Character to look up");
      if (movieCast.containsKey(name))
        textArea.setText(name +" : "+movieCast.get(name));
      else
        textArea.setText("No entry for "+ name);
}
public void update(){
      String name = askName(“Character to update");
      String old = movieCast.put(name, askName(“Actor who played
"+name));
      if (old==null)
        textArea.setText(name +" added as "+movieCast.get(name));
      else
        textArea.setText(name +" : "+old+" to "+movieCast.get(name));
}

4
Example: movieCast
public void readMovieCast(){
try {
movieCast = new HashMap<String,String>();
File filename = new File("movieCast.txt");
if(filename.exists()){
Scanner sc = new
Scanner(filename).useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()){
movieCast.put(sc.next(), sc.next());
}
sc.close();
}
}
catch(IOException ex) { … }
}
5
Iteration & “for each” loop
• How does the “for each” loop work:
for (Face face : crowd) {
face.render(canvas);
}
for (Map.Entry<String,Integer> entry : movieCast.entrySet()){
textArea.append(entry.getKey()+” as ”+entry.getValue());
}

• Different kinds of collections need different kinds of iteration:


• ArrayList A N P D F C H E K J O M L W K
• Map FamilyTree
“Prof. Porter” ⇒ Thomas Jefferson
Jack Jane Jacob Julia
“Binns” ⇒ George B. Frinch
“Tarzan” ⇒ Elmo Lincoln
Justin Joleen
“Lord Greystoke” ⇒ True Boardman

John
“Jane Porter” ⇒ Enid Markey

6
Why Iterators
• Program cannot get inside the Collection object
• “for each” loop uses Iterators
Program

hasNext
Iterator Collection
for (Face f : crowd){
next Data
}

• Iterator is implemented by the Collection


• Provides elements one at a time, e.g:
• Set.iterator() -> Iterator<t>

7
Iterators
• Operations on Iterators:
• hasNext() : returns true iff there is another value to get
• next() : returns the next value

• Standard pattern of use:

Iterator<type > itr = construct iterator of collection of type ;


while (itr.hasNext() ){
type var = itr.next();
… var …
}
• Pattern captured in the “for each” loop.
for (type var : collection of type ){
… var ….

8
Iterators and Collections
• Every Collection can construct an Iterator:
• iterator() ⇒ an Iterator over the values
• (Maps ⇒ Sets ⇒ an Iterator over keys/values/Map.Entrys )

for (Face f : crowd)


f.render(canvas);

is equivalent to:

Iterator <Face> f = crowd.iterator();


while (f.hasNext())
f.next().render(canvas);

• The compiler translates the “for each” loop into the iterator
loop.
9
Iterating through a Map
• How do you iterate through a Map? (eg, to print it out)
• A Map isn’t just a collection of items!
⇒ could iterate through the collection of keys
⇒ could iterate through the collection of values
⇒ could iterate through the collection of pairs
• Java Map allows all three!
keySet returns a Set of Keys
• for (String name : movieCast.keySet()){….
• for (String actor : movieCast.values()){….
valueSet returns a Set of values
• for (Map.Entry<String, String> entry :
movieCast.entrySet()){….
entrySet returns a Set of ‘pairs’
… entry.getKey() …
… entry.getValue()…

• Each method returns a Set collection of potentially different


types.
10
Iterating with Map.Entry
public void showAll(){
for (Map.Entry<String, String> entry : movieCast.entrySet())
textArea.append(entry.getKey() + " as " + entry.getValue()+
"\n");
}

• Map.Entry is an “inner interface” of Map


• Part of the Map interface, and can therefore
• only be obtained via call to Map.entrySet().
• Important operations:
• getKey()
• getValue()
• equals()
11
Iterator Interface
• Classes implement the Iterator interface to be
iterable. (produce an instance of Iterator)
• Iterators are not just for Collection objects:
• Iterator is an interface.
• Requires method signatures:
• hasNext() ⇒ boolean
• next() ⇒ value of the iterator’s type
• There are lots of kinds of Iterator.
eg Scanner is an Iterator (but has additional methods)
• Any object of type Iterator<type > can be used in
Iterator <…> itr = …. ;
while ( itr.hasNext() ){
…itr.next()…
}
12
Eg: Scanner as Iterator

• Scanner sc = new Scanner(new


File("myJobs.txt"));
      while (sc.hasNext() ){       
        myJobs.add(sc.next());
   }

• Scanner is special because it has additional


methods:
• hasNextInt(), hasNextBoolean, hasNextDouble, …
• nextLine(), nextInt(), nextBoolean(), nextDouble(), …
• useDelimiter(pattern) - specifies how to break file into
tokens
• … 13
Create your own Iterator
• public class NumCreator implements Iterator<Integer>{
  private int lastNum = 1,
  private int numbersToGo = 20;  // how many numbers yet to
deliver;
 
  public boolean hasNext(){
    return (numbersToGo > 0);
 }
  public Integer next(){
   lastNum = (lastNum * 13) % 97 + 1;
   numbersToGo--;
    return lastNum;
}

• Iterator<Integer> lottery = new NumCreator();


while (lottery.hasNext())
      textArea.append(lottery.next()+ "\n");
14
Exercise

• Create an Iterator that will generate an


infinite sequence of random characters.
• Hints:
• Math.round(Math.random()*26) → 0..25
• “abcdefghijklmnopqrstuvwxyz”.charAt(i) → i’th
letter of alphabet.

• Public class CharGen implements ………….{


??

15
Iterable and “for each”

• “for each” loop is not just for collections


• Any Iterable<type > object can be used in
for ( <type > var : object ) {
… var ….
}

• Iterable<type > is an interface


• Requires the method signature:
• iterator() ⇒ an Iterator<type >

16
Create your own Iterable
public class NumCreator implements Iterator<Integer>,
Iterable<Integer>{
  private int lastNum = 1,
  private int numbersToGo = 20;  // how many numbers yet to deliver;
 
public Iterator<Integer> iterator(){
   return this;
  }
    public boolean hasNext(){
    return (numbersToGo > 0);
 }
  public Integer next(){
   lastNum = (lastNum * 13) % 97 + 1;
   numbersToGo--;
    return lastNum;
}

for (Integer num : new NumCreator())


      textArea.append (num+ "\n");
17
Working with Collections
• Various Types of Collections
• Access Constraints
• Declaring and Creating collections
• Adding, removing, getting, setting, putting,….
• Iterating through collections
• [ Iterators, Iterable, and the “for each” loop ]

• What else?
• Next we will start looking at Sorting Collections

18

You might also like