A simple map: Hashtable

Similar documents
Sets and Maps. Part of the Collections Framework

CSC 1214: Object-Oriented Programming

CONTAİNERS COLLECTİONS

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Homework #10 due Monday, April 16, 10:00 PM

Class 32: The Java Collections Framework

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Lecture 6 Collections

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

CS Ananda Gunawardena

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Preview. A hash function is a function that:

Collections Framework: Part 2

9/16/2010 CS Ananda Gunawardena

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

CS11 Java. Winter Lecture 8

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

An Interface with Generics

What is the Java Collections Framework?

Collections Questions

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Generics Collection Framework

Hashing as a Dictionary Implementation

Java HashMap Interview Questions

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

Framework in Java 5. DAAD project Joint Course on OOP using Java

Collections. Collections. Collections - Arrays. Collections - Arrays

CS2110: Software Development Methods. Maps and Sets in Java

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Topic 10: The Java Collections Framework (and Iterators)

Java Collections Framework

Java Collections Framework reloaded

Administrivia. CSSS Movie Night: Zombieland & Iron Man Date: Thurs., Mar 11 Time: 6 10 pm Location: DMP 310 Free pop & popcorn for every attendee!

Collections (Java) Collections Framework

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

CS 170, Section /3/2009 CS170, Section 000, Fall

Maps,Hash(es) We need more second year reps

1.00/ Introduction to Computers and Engineering Problem Solving. Final Exam / December 21, 2005

USAL1J: Java Collections. S. Rosmorduc

Java Collections Framework. 24 April 2013 OSU CSE 1

CSE 143 Au03 Final Exam Page 1 of 15

CS2110: Software Development Methods. Maps and Sets in Java

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Habanero Extreme Scale Software Research Project

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

Collections. The Java Collections Framework. The Interfaces

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

1.00/ Introduction to Computers and Engineering Problem Solving. Final Exam / December 21, 2005

Model Solutions. COMP 103: Test May, 2013

Object-Oriented Programming with Java

Lecture 16: HashTables 10:00 AM, Mar 2, 2018

EXAMINATIONS 2016 TRIMESTER 2

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Model Solutions. COMP 103: Test April, 2013

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

The Proxy Pattern. Design Patterns In Java Bob Tarr

Java Classes - Using your classes. How the classes you write are being used

Java Collection Framework

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Collection Framework Collection, Set, Queue, List, Map 3

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Abstract Classes and Interfaces

Hash Table. Ric Glassey

Lecture 27. Binary Search Trees. Binary Search Trees

COSC A SU Assignment 1 (Abstract Data Types) Due: May 17 th, 2002

Generic classes & the Java Collections Framework. *Really* Reusable Code

Inheritance and Interfaces

CSE 143 Au03 Midterm 2 Sample Solution Page 1 of 7

Logistics. Homework 10 due tomorrow Review on Monday. Final on the following Friday at 3pm in CHEM 102. Come with questions

The Java Collections Framework and Lists in Java Parts 1 & 2

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

The class Object. Lecture CS1122 Summer 2008

Lecture 16: Case Study: The Java Collections API

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1

1.00 Lecture 32. Hashing. Reading for next time: Big Java Motivation

Collections of Objects. Object Oriented Programming Camilo López

Adam Blank Lecture 9 Autumn 2016 CSE 143. Computer Programming II

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

CIT-590 Final Exam. Name: Penn Key (Not ID number): If you write a number above, you will lose 1 point

PIC 20A Collections and Data Structures

11/27/12. CS202 Fall 2012 Lecture 11/15. Hashing. What: WiCS CS Courses: Inside Scoop When: Monday, Nov 19th from 5-7pm Where: SEO 1000

CSE 143 Au03 Midterm 2 Page 1 of 7

The Object clone() Method

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

CMSC 202H. Containers and Iterators

Programming Languages and Techniques (CIS120)

Super-Classes and sub-classes

Transcription:

Using Maps

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); 2

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 3

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. 4

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 5

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 6

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

The Map interface I Basic operations: Object put(object key, Object value) Returns the previous value associated with key, or null if there was no previous value Object 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 8

The Map interface II Optional operations: Object put(object key, Object value) (So you could implement an immutable map) void putall(map t) Adds the mappings from t to this 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 9

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 10

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 11

Map.Entry: Interface for entryset elements public interface Entry { Object getkey( ); Object getvalue( ); Object setvalue(object 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 12

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 keyvalue 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 13

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 Maps; it s the keys that you need to be careful with 14

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 15

From Hashtables to HashMaps 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 16

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) I hope to have time to give a decent lecture on Threads and synchronization 17

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

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 "John" 23 "Mary" "John" 21 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 jack "John" 23 19

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? 20

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 21

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 22

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

SortedMap Methods II SortedMap headmap(object tokey) Returns a view of the portion of this sorted map whose keys are strictly less than tokey. SortedMap submap(object fromkey, Object tokey) Returns a view of the portion of this sorted map whose keys range from fromkey, inclusive, to tokey, exclusive. SortedMap tailmap(object fromkey) Returns a view of the portion of this sorted map whose keys are greater than or equal to fromkey. 24

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 25

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. 26

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(); 27

Sets We ve talked about Sets before, and you probably remember the basic operations: int size( ); boolean isempty( ); boolean contains(object e); boolean add(object 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) 28

The End 29