Transcript of Chapter 16. Data structures that take control of organizing elements Elements not in fixed...
- Slide 1
- Chapter 16
- Slide 2
- Data structures that take control of organizing elements
Elements not in fixed positions Advantage better performance Adding
Removing Finding
- Slide 3
- Unordered collection of distinct elements Fundamental
operations Adding an element Removing an element Containment
testing (is something there) Listing arbitrary order Duplicates
Arent permitted Attempt to add ignored Attempt to remove non
existent data - ignored
- Slide 4
- Slide 5
- Hash tables Trees Uses set interface > Hash SetTree Set
- Slide 6
- Create a Hash Set of Strings Set names = new HashSet (); Adding
and deleting names.add(Romeo); names.remove(Juliet); Test to see if
element is in set if (names.contains(Juliet);
- Slide 7
- Iterator iter=names.iterator(); while (iter.hasNext()) { String
name = iter.next(); do something with the string }
- Slide 8
- for (String name: names) { do something with names { Iterating
through elements Does not visit in order inserted Set
implementation rearranges for quick location Cannot add in iterator
position Create a print method Should be usable by has or tree
- Slide 9
- Data type Associates keys and values A function from one
set(key) to another set(value) Every key has unique value A value
may have multiple keys Two kinds of implementation Hash Map Tree
Map Both implement Map Interface
- Slide 10
- Map favoriteColors = new HashMap
- Find all keys and values in map Set keySet = m.keySet();
For(String key: KeySet) { Color value=m.get(key);
System.out.println(Key + -> + value); }
- Slide 13
- Find elements in a data structure quickly No linear search
through all elements Can implement sets and maps Utilizes hash
codes Function that computes an integer value from an object
Integer value = has code Object class has a hashCode method Int h =
x.hashCode(); Collision 2 objects with same hash code Good has
functions minimizes collision Hash Code index into hash table
- Slide 14
- Simplest form Array index to hash table In array insert each
object @ location of its hash code If anything already in array
object is present
- Slide 15
- Eve Jim Joe [70068] [74478] [74656]
- Slide 16
- Problem with this idea Not possible to allocate an array that
is large enough to hold all possible integer index positions Must
reduce hash function to fit the array size int h = x.hashCode(); if
(h