LAB #8 Prepared by: Berk Soysal 2016 Winter
 Often, you will want to cycle through the elements in a collection. For example, you might want to display each element or remove an element.  The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. 2016 Winter
Iterator ListIterator Unidirectional (forward iteration) Has only next() Bidirectional (forward and backward iteration) Has next() and previous() Map, List, Set implemented Objects List implemented Objects only remove() only add(), remove() Cannot determine current position of the iterator Can determine the current position of the iterator 2016 Winter
 The Iterator interface specifies 3 methods: boolean hasNext() //returns true if this iteration has more elements E next() //returns the next element in this iteration //pre: hastNext() void remove() /*Removes from the underlying collection the last element returned by the iterator. pre: This method can be called only once per call to next. After calling, must call next again before calling remove again. */ 2016 Winter
Imagine a fence made up of fence posts and rail sections. fenceposts rails 2016 Winter
 The iterator lives on the fence posts  The data in the collection are the rails  Iterator created at the far left post  As long as a rail exists to the right of the Iterator, hasNext() is true iterator object 2016 Winter
ArrayList<String> names =new ArrayList<String>(); names.add(“Alex”); names.add(“Liz”); names.add(“Tim”); names.add(“Jack”); Iterator<String> it = names.iterator(); int i = 0; iterator object “Alex” “Liz” “Tim” “Jack” 2016 Winter
“Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 1, prints out Alex  first call to next moves iterator to next post and returns “Alex” 2016 Winter
“Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 2, prints out Liz 2016 Winter
“Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 3, prints out Tim 2016 Winter
“Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 4, prints out Jack 2016 Winter
“Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // while loop stops since call to hasNext returns false 2016 Winter
 An Iterator can be used to remove things from the Collection  Can only be called once per call to next() public void removeWordsOfLength(int len) { Iterator<String> it = myList.iterator(); while( it.hasNext() ) { String temp = it.next(); if(temp.length() == len) it.remove(); } } // myList = [“dogs”, “cat”, “hats”, “bikes”] // resulting list after removeWordsOfLength(3) ? 2016 Winter
 In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java.  The class written within is called the nested class, and the class that holds the inner class is called the outer class. class OuterClass{ class InnerClass{ } }  Inner classes are a security mechanism in Java. 2016 Winter
 We know a regular class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. 2016 Winter
You are provided an almost complete implementation of a class. Complete the implementation of the class BitList. public BitList( String s ); creates a list of bits representing the input string s. The given string, s, must be a string of 0s and 1s, otherwise the constructor must throw an exception of type IllegalArgumentException. This constructor initializes the new BitList instance to represent the value in the string. Each character in the string represents one bit of the list, with the rightmost character in the string being the low order bit. For example, given the string “1010111” the constructor should initialize the new BitList to include this list of bits: -> 1 -> 1 -> 1 -> 0 -> 1 -> 0 -> 1 2016 Winter
Use the class called Iterative. Implement the methods below. Your solutions must be iterative (i.e. uses iterators). 2016 Winter
2016 Winter
2016 Winter
• Map: an unordered collection that associates a collection of element values with a set of keys so that elements they can be found very quickly (O(1)!) – Each key can appear at most once (no duplicate keys) – A key maps to at most one value – the main operations: • put(key, value) "Map this key to that value." • get(key) "What value, if any, does this key map to?" – maps are also called: • hashes or hash tables • dictionaries • associative arrays 2016 Winter
public interface Map { Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); void putAll(Map map); void clear(); Set keySet(); Collection values(); } Basic ops Bulk ops Collection views 2016 Winter
• Map is an interface; you can't say new Map() • There are two implementations: – java.util.HashMap is best for most purposes • Preferred: Map<Key,Value> m = new HashMap<Key,Value> (); • Not: HashMap<Key,Value> m = new HashMap<Key,Value> (); 2016 Winter
Map<String,String> m = new HashMap<String,String> (); grades.put("Martin", "A"); grades.put("Nelson", "F"); grades.put(“Alex", "B"); // What grade did they get? System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); grades.put("Nelson", "W"); grades.remove("Martin"); System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); HashMap 0 2 5 HashMap grades HashMapEntry "Martin" "A" HashMapEntry "Nelson" "F" HashMapEntry “Alex" "B" 2016 Winter
public class Example { public static void main(String[] args){ Map m = new HashMap(); m.put("Newton", new Integer(1642)); m.put("Darwin", new Integer(1809)); System.out.println(m); } } Output: {Darwin=1809, Newton=1642} 2016 Winter
• public Object get(Object key) – returns the value at the specified key, or null if the key is not in the map (constant time) • public boolean containsKey(Object key) – returns true if the map contains a mapping for the specified key (constant time) • public boolean containsValue(Object val) – returns true if the map contains the specified object as a value – this method is not constant-time O(1) ... why not? 2016 Winter
• A map itself is not regarded as a collection – Map does not implement Collection interface – although, in theory, it could be seen as a collection of pairs, or a relation in discrete math terminology • Instead collection views of a map may be obtained – Set of its keys – Collection of its values (not a set... why?) 2016 Winter
• Map interface has no iterator method; you can’t get an Iterator directly • must first call either – keySet() returns a Set of all the keys in this Map – values() returns a Collection of all the values in this Map • then call iterator() on the key set or values. Examples: Iterator keyItr = grades.keySet().iterator(); Iterator elementItr = grades.values().iterator(); – If you really want the keys or element values in a more familiar collection such as an ArrayList, use the ArrayList constructor that takes a Collection as its argument ArrayList elements = new ArrayList(grades.values()); 2016 Winter
Java Tutorial Lab 8

Java Tutorial Lab 8

  • 1.
    LAB #8 Prepared by:Berk Soysal 2016 Winter
  • 2.
     Often, youwill want to cycle through the elements in a collection. For example, you might want to display each element or remove an element.  The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. 2016 Winter
  • 3.
    Iterator ListIterator Unidirectional (forwarditeration) Has only next() Bidirectional (forward and backward iteration) Has next() and previous() Map, List, Set implemented Objects List implemented Objects only remove() only add(), remove() Cannot determine current position of the iterator Can determine the current position of the iterator 2016 Winter
  • 4.
     The Iteratorinterface specifies 3 methods: boolean hasNext() //returns true if this iteration has more elements E next() //returns the next element in this iteration //pre: hastNext() void remove() /*Removes from the underlying collection the last element returned by the iterator. pre: This method can be called only once per call to next. After calling, must call next again before calling remove again. */ 2016 Winter
  • 5.
    Imagine a fencemade up of fence posts and rail sections. fenceposts rails 2016 Winter
  • 6.
     The iteratorlives on the fence posts  The data in the collection are the rails  Iterator created at the far left post  As long as a rail exists to the right of the Iterator, hasNext() is true iterator object 2016 Winter
  • 7.
    ArrayList<String> names =newArrayList<String>(); names.add(“Alex”); names.add(“Liz”); names.add(“Tim”); names.add(“Jack”); Iterator<String> it = names.iterator(); int i = 0; iterator object “Alex” “Liz” “Tim” “Jack” 2016 Winter
  • 8.
    “Alex” “Liz” “Tim”“Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 1, prints out Alex  first call to next moves iterator to next post and returns “Alex” 2016 Winter
  • 9.
    “Alex” “Liz” “Tim”“Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 2, prints out Liz 2016 Winter
  • 10.
    “Alex” “Liz” “Tim”“Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 3, prints out Tim 2016 Winter
  • 11.
    “Alex” “Liz” “Tim”“Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 4, prints out Jack 2016 Winter
  • 12.
    “Alex” “Liz” “Tim”“Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // while loop stops since call to hasNext returns false 2016 Winter
  • 13.
     An Iteratorcan be used to remove things from the Collection  Can only be called once per call to next() public void removeWordsOfLength(int len) { Iterator<String> it = myList.iterator(); while( it.hasNext() ) { String temp = it.next(); if(temp.length() == len) it.remove(); } } // myList = [“dogs”, “cat”, “hats”, “bikes”] // resulting list after removeWordsOfLength(3) ? 2016 Winter
  • 14.
     In Java,just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java.  The class written within is called the nested class, and the class that holds the inner class is called the outer class. class OuterClass{ class InnerClass{ } }  Inner classes are a security mechanism in Java. 2016 Winter
  • 15.
     We knowa regular class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. 2016 Winter
  • 16.
    You are providedan almost complete implementation of a class. Complete the implementation of the class BitList. public BitList( String s ); creates a list of bits representing the input string s. The given string, s, must be a string of 0s and 1s, otherwise the constructor must throw an exception of type IllegalArgumentException. This constructor initializes the new BitList instance to represent the value in the string. Each character in the string represents one bit of the list, with the rightmost character in the string being the low order bit. For example, given the string “1010111” the constructor should initialize the new BitList to include this list of bits: -> 1 -> 1 -> 1 -> 0 -> 1 -> 0 -> 1 2016 Winter
  • 17.
    Use the classcalled Iterative. Implement the methods below. Your solutions must be iterative (i.e. uses iterators). 2016 Winter
  • 18.
  • 19.
  • 20.
    • Map: anunordered collection that associates a collection of element values with a set of keys so that elements they can be found very quickly (O(1)!) – Each key can appear at most once (no duplicate keys) – A key maps to at most one value – the main operations: • put(key, value) "Map this key to that value." • get(key) "What value, if any, does this key map to?" – maps are also called: • hashes or hash tables • dictionaries • associative arrays 2016 Winter
  • 21.
    public interface Map{ Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); void putAll(Map map); void clear(); Set keySet(); Collection values(); } Basic ops Bulk ops Collection views 2016 Winter
  • 22.
    • Map isan interface; you can't say new Map() • There are two implementations: – java.util.HashMap is best for most purposes • Preferred: Map<Key,Value> m = new HashMap<Key,Value> (); • Not: HashMap<Key,Value> m = new HashMap<Key,Value> (); 2016 Winter
  • 23.
    Map<String,String> m =new HashMap<String,String> (); grades.put("Martin", "A"); grades.put("Nelson", "F"); grades.put(“Alex", "B"); // What grade did they get? System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); grades.put("Nelson", "W"); grades.remove("Martin"); System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); HashMap 0 2 5 HashMap grades HashMapEntry "Martin" "A" HashMapEntry "Nelson" "F" HashMapEntry “Alex" "B" 2016 Winter
  • 24.
    public class Example{ public static void main(String[] args){ Map m = new HashMap(); m.put("Newton", new Integer(1642)); m.put("Darwin", new Integer(1809)); System.out.println(m); } } Output: {Darwin=1809, Newton=1642} 2016 Winter
  • 25.
    • public Objectget(Object key) – returns the value at the specified key, or null if the key is not in the map (constant time) • public boolean containsKey(Object key) – returns true if the map contains a mapping for the specified key (constant time) • public boolean containsValue(Object val) – returns true if the map contains the specified object as a value – this method is not constant-time O(1) ... why not? 2016 Winter
  • 26.
    • A mapitself is not regarded as a collection – Map does not implement Collection interface – although, in theory, it could be seen as a collection of pairs, or a relation in discrete math terminology • Instead collection views of a map may be obtained – Set of its keys – Collection of its values (not a set... why?) 2016 Winter
  • 27.
    • Map interfacehas no iterator method; you can’t get an Iterator directly • must first call either – keySet() returns a Set of all the keys in this Map – values() returns a Collection of all the values in this Map • then call iterator() on the key set or values. Examples: Iterator keyItr = grades.keySet().iterator(); Iterator elementItr = grades.values().iterator(); – If you really want the keys or element values in a more familiar collection such as an ArrayList, use the ArrayList constructor that takes a Collection as its argument ArrayList elements = new ArrayList(grades.values()); 2016 Winter