Download presentation
Presentation is loading. Please wait.
1
L5. Necessary Java Programming Techniques
(Hashtable) Continue …… Java API
2
Hierarchy Java API java.util Class Hashtable java.lang.Object
java.util.Hashtable This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.
3
Constructor Methods Hashtable() Constructs a new, empty hashtable with a default initial capacity (11) and load factor, which is 0.75. Hashtable(int initialCapacity) Constructs a new, empty hashtable with the specified initial capacity and default load factor, which is 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. public interface Map An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
4
A simple example To retrieve a number, use the following code:
This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); To retrieve a number, use the following code: Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); }
5
Methods void clear() Clears this hashtable so that it contains no keys. boolean contains(Object value) Tests if some key maps into the specified value in this hashtable. boolean isEmpty() Tests if this hashtable maps no keys to values. boolean containsKey(Object key) Tests if the specified object is a key in this hashtable. boolean containsValue(Object value) Returns true if this Hashtable maps one or more keys to this value. Enumeration elements() Returns an enumeration of the values in this hashtable. Enumeration keys() Returns an enumeration of the keys in this hashtable.
6
Methods public interface Set extends Collection
Object get(Object key) Returns the value to which the specified key is mapped in this hashtable. Object put(Object key, Object value) Maps the specified key to the specified value in this hashtable. Objec remove(Object key) Removes the key (and its corresponding value) from this hashtable Set keySet() Returns a Set view of the keys contained in this Hashtable public interface Set extends Collection A collection that contains no duplicate elements.
7
Demo
8
Exercise Make a java program that can store employees’ data (name and id) to a hash table and do the operations shown in the display below. HashTableApplet.java (optional) After finish Ex 1. please continue to make a java application program to the same problem above.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.