Using Maps. 2 A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Hashing. 2 Searching Consider the problem of searching an array for a given value –If the array is not sorted, the search requires O(n) time If the value.
Using Maps. A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures and algorithms in the collection framework 1.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
A Introduction to Computing II Lecture 11: Hashtables Fall Session 2000.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Set and Map IS 313, Skeletons  Useful coding patterns  Should understand how and why they work how to use  possible quiz material.
Maps Nick Mouriski.
Week 9 - Friday.  What did we talk about last time?  Collisions  Open addressing ▪ Linear probing ▪ Quadratic probing ▪ Double hashing  Chaining.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Dwight Deugo Nesa Matic
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
Hashing. Searching Consider the problem of searching an array for a given value If the array is not sorted, the search requires O(n) time If the value.
Hashing By Emily Nelson. The Official Definition Using a hash function to turn some kind of data in relatively small integers or Strings The “hash code”
Building Java Programs Generics, hashing reading: 18.1.
Sets and Maps Chapter 9.
Using Maps.
Using Maps.
Introduction to Collections
Introduction to Collections
CSE 373: Data Structures and Algorithms
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Using Maps.
Using Maps.
Introduction to Collections
L5. Necessary Java Programming Techniques
Introduction to Collections
Sets and Maps Chapter 9.
Hashing in java.util
Part of the Collections Framework
Presentation transcript:

Using Maps

2 A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put (key, value ); To retrieve a value from a Hashtable, use: value = table.get( key );

3 Example use of a Hashtable import java.util.*; public class HashtableUser { public static void main(String[] args) { Hashtable table = new Hashtable (); table.put("one", "un"); table.put("two", "deux"); table.put("three", "trois"); System.out.println("two -> " + table.get("two")); System.out.println("deux -> " + table.get("deux")); } } two -> deux deux -> null

4 Hashtable constructors Hashtable() Constructs a new, empty Hashtable with a default capacity ( 11 ) and default load factor ( 0.75 ). Hashtable(int initialCapacity ) Constructs a new, empty Hashtable with the specified initial capacity and the default load factor ( 0.75 ). Hashtable(int initialCapacity, float loadFactor ) Constructs a new, empty Hashtable with the specified initial capacity and the specified load factor. Hashtable(Map t ) Constructs a new Hashtable with the same mappings as the given Map.

5 Which constructor should you use? This is basically a question of efficiency A hash table that is mostly empty wastes space If a hash table is nearly full, some searches may take a very long time The initial capacity of a hash table is the number of entries that it can hold initially The load factor is a measure of how full it is A load factor of 75% is usually a good compromise If the table gets fuller than the load factor, Java creates a new, larger hash table and rehashes everything Rehashing is an expensive operation

6 Hashtable constructors (again) Hashtable() Use if the default values are good enough Hashtable(int initialCapacity ) Use if you have some idea how many entries to expect Try to ensure it won’t be more than 75% full If space is not an issue, double or triple the size Hashtable(int initialCapacity, float loadFactor ) Use if you are trying to be super efficient Requires careful experimentation and tuning Hashtable(Map t ) Use to make a Hashtable from some other map Initial capacity = 2*(size of t ), load factor = 0.75

7 The Collections framework Hashtable is an old (pre-Collections) class Hashtable has been retrofitted to implement the Map interface Collection SortedSet ListSet SortedMap Map Hashtable

8 The Map interface I Basic operations: V put(K key, V value ) Returns the previous value associated with key, or null if there was no previous value V get(Object key ) Returns null if the key was not found A return value of null may not mean the key was not found (some implementations of Map allow null keys and values) Tests: boolean containsKey(Object key ) boolean containsValue(Object value ) Warning: probably requires linear time! boolean isEmpty() boolean equals(Object o ) Returns true if o is also a map and has the same mappings

9 The Map interface II Optional operations: V put(K key, V value ) (So you could implement an immutable map) void putAll(Map t ) Adds the mappin gs from t to t his map void clear() Object remove(Object key ) Returns the value that was associated with the key, or null Other: int size() Returns the number of key-value mappings int hashCode() Returns a hash code value for this map

10 Optional operations Question: How can a method declared in an interface be optional? Answer: you have to implement it, but the implementation may be something like this: public void remove(Object key) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } In fact, HashMap extends AbstractMap, which provides many of the map operations, and implements the optional operations exactly this way

11 Map views Set keySet() Returns a set view of the keys contained in this map. Collection values() Returns a collection view of the values contained in this map Can’t be a set—keys must be unique, but values may be repeated Set > entrySet() Returns a set view of the mappings contained in this map. A view is dynamic access into the Map If you change the Map, the view changes If you change the view, the Map changes The Map interface does not provide any Iterators However, there are iterators for the above Sets and Collections

12 Map.Entry : Interface for entrySet elements public interface Entry { K getKey( ); V getValue( ); V setValue(V value); } This is a small interface for working with the Collection returned by entrySet( ) Can get elements only from the Iterator, and they are only valid during the iteration

13 Constructors Map is an interface, so it cannot require any constructors However, Java always supplies: A no-argument constructor for each Map type A constructor that takes a Map argument, and copies its key- value pairs into the new Map If you ever implement your own Map class, you should define these constructors Defining your own Map class is easy: class MyMap implements Map {... } There are, however, a lot of methods to implement

14 Hazards I In order for a Hashtable to work correctly, equals must be defined properly on the keys hashCode must be defined properly on the keys This is not a problem if you use Strings for the keys (this is extremely common) If you use objects of some other class as your keys, you must make sure equals and hashCode are properly defined Note: equals and hashCode are properly defined for all of Java’s Map s; it’s the keys that you need to be careful with

15 Hazards II You should use immutable objects (like Strings) as keys If you put a value into a hash table with a mutable key, and you change the key, what happens? Answer: Nothing good! Special case #1: A map may not contain itself as a key Special case #2: A map may contain itself as a value, but equals and hashCode are no longer well-defined These special cases are really weird and you will probably never get anywhere near them

16 From Hashtable s to HashMap s Hashtable has been around a long time, but HashMap is new with Java 1.2 So why am I teaching you the old stuff? Actually, except for the constructors, I’ve been talking about the Map interface, which both Hashtable and HashMap implement Both are cloneable (more on this later) and serializable Differences: Hashtable is synchronized; HashMap is not HashMap permits null values and (one) null key; Hashtable does not

17 synchronized Java supports multiple Threads A Thread is an execution sequence Having multiple Threads means that Java appears to be doing many different things all at the same time Threads can interfere with each other unless they are carefully synchronized (prevented from both using the same data at the same time) This can be an issue with GUIs, which run in a different Thread from the rest of the program If you use a hash table from an event handler, use a Hashtable (which is synchronized) instead of a HashMap (which is not)

18 Copying objects In Java, you seldom copy objects, you just copy references to objects Person jack = john; jack.name = "Jack"; jack Person mary = new Person("Mary", 21); Person john = new Person("John", 23, mary); mary.setSpouse(john); "John" 23 john "John" 21 "Mary" Suppose, however, that you really do want to make a copy; how do you do it? Answer: you clone the object "Jack"

19 The Cloneable interface Cloneable, like Serializable, is a marker interface: it doesn't require any methods It does, however, allow you to use the clone method class Person implements Cloneable {... }... Person jack = john.clone(); clone() makes a shallow copy If you want a deep copy, you have to write a lot more code Avoid making copies if possible; it’s not easy and it’s expensive "John" 23 john "John" 21 "Mary" jack "John" 23

20 Copy constructors Rather than use cloneable, it’s usually better to write a copy constructor—a constructor that takes an object as a parameter and makes another object just like it Example: Person jack = new Person(john); There is nothing magic about a copy constructor—it’s up to you to make a deep copy rather than a shallow copy Person (Person original) { this.name = original.name; this.spouse = new Person(original.spouse); this.spouse.spouse = this; // why? } Does this actually work?

21 The SortedMap interface A hash table keeps elements in an (apparently) random order Sometimes you want the keys of a map to be in sorted order (e.g. phone book, dictionary) A map can be implemented with a hash table, but it doesn’t have to be The SortedMap interface implements the Map interface and provides additional methods For efficiency, you want an implementation that keeps its elements in some kind of order

22 Requirements for SortedMap A SortedMap keeps its elements in the order of increasing key values Therefore, it must be possible to sort the keys! This means: The keys must be objects of a type that implement the Comparable interface (or be given a Comparator ) Keys must be mutually comparable (e.g. you can’t compare a String to a Button ) The ordering must be consistent with equals All implementations of SortedMap should supply four constructors We’ll see an example of these shortly

23 SortedMap Methods I Comparator comparator() Returns the comparator associated with this sorted map, or null if it uses its keys' natural ordering. K firstKey() Returns the first (lowest) key currently in this sorted map. K lastKey() Returns the last (highest) key currently in this sorted map.

24 SortedMap Methods II SortedMap headMap(K toKey) Returns a view of the portion of this sorted map whose keys are strictly less than toKey. SortedMap subMap(K fromKey, K toKey) Returns a view of the portion of this sorted map whose keys range from fromKey, inclusive, to toKey, exclusive. SortedMap tailMap(K fromKey) Returns a view of the portion of this sorted map whose keys are greater than or equal to fromKey.

25 The TreeMap class TreeMap implements SortedMap TreeMap is the only implementation that Java provides for SortedMap Question: Since there’s only one implementation, why bother to have a separate interface? Answer: To give you the flexibility to define additional kinds of sorted map, if you wish to You probably won’t—but the flexibility is there

26 TreeMap constructors TreeMap() Constructs a new, empty map, sorted according to the keys' natural order. TreeMap(Comparator c) Constructs a new, empty map, sorted according to the given comparator. TreeMap(Map m) Constructs a new map containing the same mappings as the given map, sorted according to the keys' natural order. TreeMap(SortedMap m) Constructs a new map containing the same mappings as the given SortedMap, sorted according to the same ordering.

27 Quick summary Interfaces (cannot instantiate): Map SortedMap Serializable Cloneable Classes (can instantiate): Hashtable HashMap TreeMap As always, it’s best to avoid exposing the implementation; hence: Map myMap = new HashMap (); But probably not: Map myMap = new TreeMap ();

28 Sets We’ve talked about Sets before, and you probably remember the basic operations: int size( ); boolean isEmpty( ); boolean contains(Object e); boolean add(E e); boolean remove(Object e); Iterator iterator( ); However, Set is an interface, not a class There are two supplied implementations: HashSet (for when you don’t care about the order of elements) and TreeSet (for when you do)

29 The End