Eva Sys wants YOUR input NOW Wikimedia Commons

  • Slides: 28
Download presentation

Eva. Sys wants YOUR input NOW! [Wikimedia Commons] Gemeinsames Ziel: Studierbarkeit verbessern In Eva.

Eva. Sys wants YOUR input NOW! [Wikimedia Commons] Gemeinsames Ziel: Studierbarkeit verbessern In Eva. Sys-Freitext, bitte folgende Fragen [Perle-TAP] beantworten: 1. Wodurch lernen Sie in dieser Veranstaltung am meisten? 2. Was erschwert Ihr Lernen? 3. Welche Verbesserungsvorschläge haben Sie für die hinderlichen Punkte?

Five-Minute Review 1. What debugging strategies do you know? 2. When should you use

Five-Minute Review 1. What debugging strategies do you know? 2. When should you use assertions? 3. What is a Hoare Triple? 4. What is multiple inheritance? Does Java support it? 5. What is an interface in Java? 5

Programming – Lecture 11 Collection Classes (Chapter 13) • Hash. Map class • •

Programming – Lecture 11 Collection Classes (Chapter 13) • Hash. Map class • • • Aside: Computational complexity, Big-O Bucket hashing Java Collections Framework – lists, sets, maps Iteration in Collections Map hierarchy Collections class • Principles of OO design 6

Hash. Map: mapping from a set of unique keys to values new Hash. Map<>(

Hash. Map: mapping from a set of unique keys to values new Hash. Map<>( ) Creates a new Hash. Map object that is initially empty. map. put(key, value) Sets the association for key in the map to value. map. get(key) Returns the value associated with key, or null if none. Generic types for keys and values: Hash. Map<String, Integer> uses strings as keys and int's as values 14

Postal. Lookup public void run() { Hash. Map<String, String>(); Hash. Map<String, String> state. Map

Postal. Lookup public void run() { Hash. Map<String, String>(); Hash. Map<String, String> state. Map = new Hash. Map<>(); private void init. State. Map(Hash. Map<String, String> map) { init. State. Map(state. Map); map. put("AL", "Alabama"); while (true) { map. put("AK", "Alaska"); String code = read. Line("Enter two-letter state abbreviation: "); map. put("AZ", "Arizona"); if (code. length() == 0) break; . . . String state = state. Map. get(code); map. put("FL", "Florida"); if (state == null) { map. put("GA", "Georgia"); println(code + " is not a known state abbreviation"); map. put("HI", "Hawaii"); } else {. . . println(code + " is " + state); map. put("WI", "Wisconsin"); state code state. Map } map. put("WY", "Wyoming"); map } Hawaii null VE WI HI Wisconsin } } Postal. Lookup Enter HI is Enter WI is Enter VE is Enter two-letter state abbreviation: HI Hawaii two-letter state abbreviation: WI Wisconsin two-letter state abbreviation: VE not a known state abbreviation two-letter state abbreviation: AL=Alabama AK=Alaska AZ=Arizona . . . FL=Florida GA=Georgia HI=Hawaii . . . WI=Wisconsin WY=Wyoming skip simulation 17

Implementing put and get map. put(key, value) Sets the association for key in the

Implementing put and get map. put(key, value) Sets the association for key in the map to value. Returns the value associated map. get(key) with key, or null if none. First approach: linear search in parallel arrays Efficiency? I. e. , how costly is each get/put in terms of computation time? 18

Aside: Computational Complexity What is a good cost measure? • Not: seconds or clock

Aside: Computational Complexity What is a good cost measure? • Not: seconds or clock cycles • Instead: count operations, relative to problem size • An operation may be arbitrarily complex/abstract, but is assumed to take constant time • Thus, ignore constant factors • Are (at least here) not interested in absolute number of operations • Instead, want to know how the operation count increases if problem size increases, and asymptotically approaches ∞ • Typically, are interested in worst case 19 • May also be interested in average case

Aside: Computational Complexity For maps: • Problem size N = number of elements Implementing

Aside: Computational Complexity For maps: • Problem size N = number of elements Implementing maps with parallel arrays: • put takes a constant number of operations; thus, may consider put as 1 operation • put “takes constant time”; denote this as O(1) • get takes at most N (on average N/2) operations • get "takes linear time", "has linear (asymptotic) complexity”; denote this as O(N) 20

Bachmann-Landau Notation – Big-O Algorithm has complexity O(f(N)): For large N, the growth rate

Bachmann-Landau Notation – Big-O Algorithm has complexity O(f(N)): For large N, the growth rate of its run time behaves as the growth rate of f(N) Formally: let t(N) denote run time for problem size N. t(N)∈O(f(N)) iff ∃c∈ℝ, N 0∈ℕ. ∀N > N 0. t(N) < c f(N) Simplify f(N) as much as possible: • Eliminate parts that disappear as N becomes large • Eliminate constant factors Thus don't write O(2 N + 3 N 2 + log N 3), but simply O(N 2). (Mathematically, both would be equivalent, but we always ask for the simplified form only. ) 21 But don't forget: in practice, constants matter as well. What is really best algorithm depends on actual problem sizes.

Assume problem size N = n, loop body O(1) for (int i = 0;

Assume problem size N = n, loop body O(1) for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) {. . . loop body. . . } } for (int k = 1; k <= n; k *= 2) {. . . loop body. . . } for (int i = 0; i < 100; i++) { for (int j = 0; j < i; j++) {. . . loop body. . . } } 23

Please visit pingo. upb. de/ 643250 https: //xkcd. com/2098

Please visit pingo. upb. de/ 643250 https: //xkcd. com/2098

Implementing put and get map. put(key, value) Sets the association for key in the

Implementing put and get map. put(key, value) Sets the association for key in the map to value. Returns the value associated map. get(key) with key, or null if none. 1) Linear search in parallel arrays O(N) 2) Binary search in parallel arrays O(log N) 3) Table lookup in a two-dimensional array O(1) But requires space O(A 2), for A = # letters 4) Bucket hashing O(1) on average if "enough" buckets 25 (i. e. , if linked lists have average length O(1))

Hashing Each object hash code • To get it: hash. Code(), returns int •

Hashing Each object hash code • To get it: hash. Code(), returns int • If objects have equal values, the objects have same hash codes • Hash codes must be unique for given object • Collision: different values are mapped to same hash code • Want hash function that minimizes collisions Bucket hashing: • Map hash codes (of keys) to buckets • In bucket, linked list of (key, value) pairs 26

Bucket Hashing 0 1 2 3 4 5 6 CA CA CA CO DE

Bucket Hashing 0 1 2 3 4 5 6 CA CA CA CO DE KS ID rest CO DE ID the keys CO DE are added CO state. Map. put("AL", "Alabama") state. Map. put("AK", "Alaska") state. Map. put("AZ", "Arizona") The of similarly. WY CO MT NC CA DE KS NJ ID CA CO MT NC DE KS NJ ID CA CO MT DE KS ID North New California Wyoming Delaware Colorado Montana Kansas Idaho Carolina Jersey North New California Delaware Colorado Montana Kansas Idaho Carolina Jersey New California Delaware Colorado Montana Kansas Idaho Jersey California Delaware Colorado Montana Kansas Idaho null "AL". hash. Code() 2091 "AK". hash. Code() 2090 "AZ". hash. Code() 2105 null IL MN OH ND NY SC TN VA IL MN OH ND NY SC TN IL MN OH ND NY SC IL MN OH ND NY Math. abs(2090) Math. abs(2091) 5 Math. abs(2105) IL IL IL % 7 IL 4 MN ND NY MN North South Illinois Minnesota New Tennessee Virginia Ohio York Carolina Dakota North South Illinois Minnesota New Tennessee Ohio York Carolina Dakota North South Illinois Minnesota New Ohio York Carolina Dakota North Illinois Minnesota New Ohio York Dakota null MO MA SD NE HI MO MA HI South Massachusetts Hawaii Nebraska Missouri Dakota Massachusetts Nebraska Hawaii Missouri Massachusetts Missouri Hawaii Massachusetts Hawaii null NM UT MI IN NM MI IN IN New Michigan Indiana Utah Mexico New Michigan Indiana Mexico Michigan Indiana null California Delaware Colorado Kansas Idaho North Illinois Minnesota New York Dakota California Delaware Colorado Idaho Illinois Minnesota New York California Delaware Colorado Illinois Minnesota California Colorado California null Illinois The key null "AL" goes in bucket 5. "AK" therefore 4. "AZ" null Because bucket you 5 already contains "AL", HI Suppose call state. Map. get("HI") the Hawaii"AZ" must be added to the chain. "HI". hash. Code() 2305 null Math. abs(2305) % 7 2 The key "HI" must therefore be in bucket 2 and can be located by searching the chain. WA WV OR OK AR AK PA TX RI IA WA OR OK AR AK PA TX RI IA OR OK AR AK PA IA OR OK AR AK IA AR AK AK Rhode West Pennsylvania Washington Oklahoma Arkansas Oregon Alaska Texas Iowa Virginia Island Rhode Pennsylvania Washington Oklahoma Arkansas Oregon Alaska Texas Iowa Island Rhode Pennsylvania Oklahoma Arkansas Oregon Alaska Iowa Island Pennsylvania Oklahoma Arkansas Oregon Alaska Iowa Oklahoma Arkansas Alaska Iowa Arkansas Alaska null null null AL MD GA NH NV CT AZ WI AL MD GA NH NV CT AZ AL MD GA CT AZ AL AZ AL New Connecticut Alabama Wisconsin Maryland Arizona Georgia Nevada Hampshire New Connecticut Alabama Maryland Arizona Georgia Nevada Hampshire Connecticut Alabama Maryland Arizona Georgia Nevada Connecticut Alabama Maryland Arizona Georgia Connecticut Alabama Arizona Alabama null null FL MS ME KY VT LA FL ME MS KY LA FL ME KY LA FL KY FL Mississippi Florida Louisiana Kentucky Vermont Maine Mississippi Florida Louisiana Kentucky Maine Florida Louisiana Kentucky Florida null null skip simulation 32

Bucket Hashing public class Simple. String. Map { private static final int N_BUCKETS =

Bucket Hashing public class Simple. String. Map { private static final int N_BUCKETS = 7; private Hash. Entry[] bucket. Array; /** Creates a new Simple. String. Map with no key/value pairs */ public Simple. String. Map() { bucket. Array = new Hash. Entry[N_BUCKETS]; } /** * Sets the value associated with key. Any previous value for key is lost. * @param key The key used to refer to this value * @param value The new value to be associated with key */ public void put(String key, String value) { int bucket = Math. abs(key. hash. Code()) % N_BUCKETS; Hash. Entry entry = find. Entry(bucket. Array[bucket], key); if (entry == null) { entry = new Hash. Entry(key, value); entry. set. Link(bucket. Array[bucket]); bucket. Array[bucket] = entry; } else { entry. set. Value(value); } } page 1 of 4 skip code

Bucket Hashing /** * Retrieves the value associated with key, or null if no

Bucket Hashing /** * Retrieves the value associated with key, or null if no such value exists. * @param key The key used to look up the value * @return The value associated with key, or null if no such value exists */ public String get(String key) { int bucket = Math. abs(key. hash. Code()) % N_BUCKETS; Hash. Entry entry = find. Entry(bucket. Array[bucket], key); if (entry == null) { return null; } else { return entry. get. Value(); } } } /* * Scans the entry chain looking for an entry that matches the specified key. * If no such entry exists, find. Entry returns null. */ private Hash. Entry find. Entry(Hash. Entry entry, String key) { while (entry != null) { if (entry. get. Key(). equals(key)) return entry; entry = entry. get. Link(); } return null; } page 2 of 4 skip code

Bucket Hashing /* Package-private class: Hash. Entry */ /* * This class represents a

Bucket Hashing /* Package-private class: Hash. Entry */ /* * This class represents a pair of a key and a value, along with a reference * to the next Hash. Entry in the chain. The methods exported by the class * consist only of getters and setters. */ class Hash. Entry { /* Private instance variables */ private String key; /* The key component for this Hash. Entry */ private String value; /* The value component for this Hash. Entry */ private Hash. Entry link; /* The next entry in the chain */ /* Creates a new Hash. Entry for the specified key/value pair */ public Hash. Entry(String key, String value) { this. key = key; this. value = value; } /* Returns the key component of a Hash. Entry */ public String get. Key() { return key; } page 3 of 4 skip code

Bucket Hashing /* Returns the value component of a Hash. Entry */ public String

Bucket Hashing /* Returns the value component of a Hash. Entry */ public String get. Value() { return value; } /* Sets the value component of a Hash. Entry to a new value */ public void set. Value(String value) { this. value = value; } /* Returns the next link in the entry chain */ public Hash. Entry get. Link() { return link; } /* Sets the link to the next entry in the chain */ public void set. Link(Hash. Entry link) { this. link = link; } } page 4 of 4

Java Collections Framework Maps + lists (ordered) + sets (unordered) «interface» Iterable «interface» Collection

Java Collections Framework Maps + lists (ordered) + sets (unordered) «interface» Iterable «interface» Collection «interface» List Abstract. Collection Abstract. List Array. List Linked. List . . . and much more «interface» Set Abstract. Set Hash. Set «interface» Sorted. Set Tree. Set 41

Iteration in Collections import java. util. *; Iterator< type > iterator = collection. iterator();

Iteration in Collections import java. util. *; Iterator< type > iterator = collection. iterator(); while (iterator. has. Next()) { type element = iterator. next(); . . . statements that process this particular element. . . } Simplify to for-each: for (type element : collection) {. . . statements that process this particular element. . . } 45

Map Hierarchy «interface» Map Abstract. Map Hash. Map «interface» Sorted. Map Tree. Map 47

Map Hierarchy «interface» Map Abstract. Map Hash. Map «interface» Sorted. Map Tree. Map 47

Iteration Order in Hash. Map private void list. Keys(Map<String, String> map, int n) {

Iteration Order in Hash. Map private void list. Keys(Map<String, String> map, int n) { String class. Name = map. get. Class(). get. Name(); int last. Dot = class. Name. last. Index. Of(". "); String short. Name = class. Name. substring(last. Dot + 1); println("Using " + short. Name + ", the keys are: "); int i = 0; for (String key : map. key. Set()) { print(" " + key); if (++i % n == 0) println(); } } Map. Iterator Using Hash. Map, the SC VA LA GA DC OH DE MS WV HI FL KS NH MT WI CO OK NE IN AL CA UT WY ND keys are: MN KY WA IL SD AK TN ID NV MI MD TX PA AR CT NJ OR RI VT ME NM NC AZ MO MA NY PR IA 48

Iteration Order in Tree. Map private void list. Keys(Map<String, String> map, int n) {

Iteration Order in Tree. Map private void list. Keys(Map<String, String> map, int n) { String class. Name = map. get. Class(). get. Name(); int last. Dot = class. Name. last. Index. Of(". "); String short. Name = class. Name. substring(last. Dot + 1); println("Using " + short. Name + ", the keys are: "); int i = 0; for (String key : map. key. Set()) { print(" " + key); if (++i % n == 0) println(); } } Map. Iterator Using Tree. Map, the AK AL AR AZ CA CO ID IL IN KS KY LA MT NC ND NE NH NJ PR RI SC SD TN TX keys are: CT DC DE FL MA MD ME MI NM NV NY OH UT VA VT WA GA MN OK WI HI MO OR WV IA MS PA WY 49

Iteration Order in Tree. Map private void list. Keys(Map<String, String> map, int n) {

Iteration Order in Tree. Map private void list. Keys(Map<String, String> map, int n) { String class. Name = map. get. Class(). get. Name(); int last. Dot = class. Name. last. Index. Of(". "); String short. Name = class. Name. substring(last. Dot + 1); println("Using " + short. Name + ", the keys are: "); Iterator<String> iterator = map. key. Set(). iterator(); for (int i = 1; iterator. has. Next(); i++) { print(" " + iterator. next()); if (i % n == 0) println(); } } Map. Iterator Using Tree. Map, the AK AL AR AZ CA CO ID IL IN KS KY LA MT NC ND NE NH NJ PR RI SC SD TN TX keys are: CT DC DE FL MA MD ME MI NM NV NY OH UT VA VT WA GA MN OK WI HI MO OR WV IA MS PA WY 50

List Methods in Collections Class binary. Search( list, key) sort(list) Finds key in a

List Methods in Collections Class binary. Search( list, key) sort(list) Finds key in a sorted list using binary search. min(list) Returns the smallest value in a list. max(list) Returns the largest value in a list. reverse(list) Reverses the order of elements in a list. shuffle(list) swap(list, p 1, p 2) Randomly rearranges the elements in a list. Exchanges the elements at index positions p 1 and p 2. replace. All( list, x 1, x 2) Replaces all elements matching x 1 with x 2. Sorts a list into ascending order. java. util provides similar Arrays class 52

Principles of OO Design Packages should be • Unified • Simple • Sufficient •

Principles of OO Design Packages should be • Unified • Simple • Sufficient • Flexible • Stable • Well-documented 54

Summary • Java Collections Framework is unified architecture for representing and manipulations collections •

Summary • Java Collections Framework is unified architecture for representing and manipulations collections • Important interfaces are lists (indexed), sets (not indexed) and maps (map keys to values) • Array. List is more efficient for selecting particular element or for searching an element; Linked. List is more efficient for adding/removing elements • Hash. Set builds on hashing (fast, unordered), Tree. Set builds on binary trees (slower, ordered) • Lists and sets allow iteration (for-each) • Packages should be unified, simple, sufficient, flexible, and stable 55