Java Tutorial/Collections/Hashtable Basics — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:05, 1 июня 2010
Содержание
- 1 Adding Key-Value Pairs
- 2 Check if a particular key exists in Java Hashtable
- 3 Check if a particular value exists in Java Hashtable
- 4 Cloning Hash Tables
- 5 contains() and containsValue(): check to see if a specific value is found within the Hashtable
- 6 Copying all the key-value pairs from one Hashtable (or any Map) into another Hashtable: the putAll() method
- 7 Counting Word Occurrences with a hash table
- 8 Creating Hash Tables
- 9 Displaying Hash Table Contents
- 10 Fetching Keys and Values: the get() method
- 11 Finding Elements
- 12 Get all keys and elements from a hash table
- 13 Get Collection of Values from Hashtable
- 14 Get Set view of Keys from Hashtable
- 15 Getting elements (key-value pairs) from a Hashtable: the entrySet() method
- 16 Hashtable Immutability: to make the table read-only using Collections.unmodifiableMap(Map map)
- 17 Iterate through keys of Java Hashtable
- 18 Iterate through values of Java Hashtable
- 19 Remove all values from Java Hashtable
- 20 Remove value from Java Hashtable
- 21 Removing Key-Value Pairs: call the remove() method with the specific key as its argument
- 22 Scan the content of a hashtable
- 23 Sizing Hash Tables
- 24 Sort keys in an Hashtable
- 25 To get rid of all key-value pairs: call the clear() method
- 26 To perform some operation on all keys: the keys() or keySet() methods
- 27 Use iterators with a Hashtable.
- 28 uses a generic Hashtable to store the names of bank depositors and their current balances
- 29 Using the elements() or the values() method to get the set of all the values in the hash table
Adding Key-Value Pairs
public Object put(Object key, Object value)
key3 : value3 key2 : value2 key1 : value1
Check if a particular key exists in Java Hashtable
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
boolean blnExists = ht.containsKey("2");
System.out.println("2 exists in Hashtable ? : " + blnExists);
}
}
Check if a particular value exists in Java Hashtable
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
boolean blnExists = ht.contains("Two");
System.out.println("Two exists in Hashtable ? : " + blnExists);
}
}
Cloning Hash Tables
The Hashtable class provides its own implementation of the clone() method.
import java.util.Hashtable;
public class MainClass {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("key1", "value1");
table.put("key2", "value2");
table.put("key3", "value3");
Hashtable tableCopy = (Hashtable)table.clone();
System.out.println(tableCopy);
}
}
{key3=value3, key2=value2, key1=value1}
contains() and containsValue(): check to see if a specific value is found within the Hashtable
public boolean contains(Object value)
public boolean containsValue(Object value)
true
Copying all the key-value pairs from one Hashtable (or any Map) into another Hashtable: the putAll() method
If any keys already exist in the hash table, their value will be replaced if they are also found in the passed-in map.
public void putAll(Map map)
{key6=value6, key5=value5, key4=value4, key3=value3, key2=value2, key1=value1}
Counting Word Occurrences with a hash table
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
public class MainClass {
static final Integer ONE = new Integer(1);
public static void main(String args[]) throws IOException {
Hashtable map = new Hashtable();
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
processLine(line, map);
}
Enumeration e = map.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + map.get(key));
}
}
static void processLine(String line, Map map) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
addWord(map, st.nextToken());
}
}
static void addWord(Map map, String word) {
Object obj = map.get(word);
if (obj == null) {
map.put(word, ONE);
} else {
int i = ((Integer) obj).intValue() + 1;
map.put(word, new Integer(i));
}
}
}
Creating Hash Tables
A Hashtable is a Dictionary that relies on a hashing algorithm to convert keys.
Creating a Hashtable can be done with one of four constructors; the first three are
public Hashtable()
public Hashtable(int initialCapacity)
public Hashtable(int initialCapacity, float loadFactor)
Displaying Hash Table Contents
The Hashtable class overrides the toString() method of the Object class
public String toString()
{key3=value3, key2=value2, key1=value1}
Fetching Keys and Values: the get() method
public Object get(Object key)
key3 : value3 key2 : value2 key1 : value1
Finding Elements
import java.util.Hashtable;
public class MainClass {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("key1", "value1");
table.put("key2", "value2");
table.put("key3", "value3");
System.out.println(table.containsKey("key3"));
}
}
true
Get all keys and elements from a hash table
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
public class MainClass {
public static void main(String[] args) {
String data;
String msg;
Hashtable h = new Hashtable(20);
System.out.println(h.put("one", new Integer(1)));
System.out.println(h.put("name", "A"));
System.out.println(h.put("date", new Date()));
System.out.println(h.put("one", new Integer(4)));
Enumeration e = h.keys();
while (e.hasMoreElements())
System.out.println(e.nextElement());
e = h.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Get Collection of Values from Hashtable
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String,String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Collection c = ht.values();
Iterator itr = c.iterator();
while (itr.hasNext()){
System.out.println(itr.next());
}
c.remove("One");
Enumeration e = ht.elements();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Get Set view of Keys from Hashtable
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Hashtable<String,String> ht = new Hashtable<String,String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Set st = ht.keySet();
Iterator itr = st.iterator();
while (itr.hasNext()){
System.out.println(itr.next());
}
st.remove("2");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
/*
3
2
1
3
1
*/
Getting elements (key-value pairs) from a Hashtable: the entrySet() method
public Set entrySet()
key3 : value3 key2 : value2 key1 : value1
Hashtable Immutability: to make the table read-only using Collections.unmodifiableMap(Map map)
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
public class MainClass {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("key1", "value1");
table.put("key2", "value2");
table.put("key3", "value3");
Map m = Collections.unmodifiableMap(table);
m.put("key3", "value3");
System.out.println(m);
}
}
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1286) at MainClass.main(MainClass.java:14)
Iterate through keys of Java Hashtable
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Iterate through values of Java Hashtable
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.elements();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Remove all values from Java Hashtable
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
ht.clear();
System.out.println(ht.size());
}
}
Remove value from Java Hashtable
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Object obj = ht.remove("2");
System.out.println(obj + " was Removed ");
Enumeration e = ht.elements();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Removing Key-Value Pairs: call the remove() method with the specific key as its argument
public Object remove(Object key)
{key3=value3, key2=value2}
Scan the content of a hashtable
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String args[]) {
Hashtable<String,String> hash = new Hashtable<String,String>();
hash.put("1","one");
hash.put("2","two");
hash.put("3","three");
Enumeration keys = hash.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = hash.get(key);
System.out.println(key+" : "+value);
}
}
}
Sizing Hash Tables
public int size()
public boolean isEmpty()
false 3
Sort keys in an Hashtable
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public class Main {
public static void main(String args[]) {
Hashtable<String, String> h = new Hashtable<String, String>();
h.put("a", "b");
h.put("c", "d");
h.put("e", "f");
for (String str : h.keySet()) {
System.out.println(str);
}
List<String> v = new ArrayList<String>(h.keySet());
Collections.sort(v);
for (String str : v) {
System.out.println(str + " " + (String) h.get(str));
}
}
}
To get rid of all key-value pairs: call the clear() method
public void clear()
{}
To perform some operation on all keys: the keys() or keySet() methods
public Enumeration keys()
public Set keySet()
key3 : value3 key2 : value2 key1 : value1 [key3, key2, key1]
Use iterators with a Hashtable.
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
class HTDemo2 {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
String str;
double bal;
balance.put("A", 3434.34);
balance.put("B", 123.22);
balance.put("C", 1378.00);
balance.put("D", 99.22);
balance.put("E", -19.08);
Set<String> set = balance.keySet();
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
str = itr.next();
System.out.println(str + ": " + balance.get(str));
}
System.out.println();
bal = balance.get("A");
balance.put("A", bal + 1000);
System.out.println("A"s new balance: " + balance.get("A"));
}
}
uses a generic Hashtable to store the names of bank depositors and their current balances
import java.util.Enumeration;
import java.util.Hashtable;
class HTDemo {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Enumeration<String> names;
String str;
double bal;
balance.put("A", 3434.34);
balance.put("B", 123.22);
balance.put("C", 1378.00);
balance.put("D", 99.22);
balance.put("E", -19.08);
names = balance.keys();
while (names.hasMoreElements()) {
str = names.nextElement();
System.out.println(str + ": " + balance.get(str));
}
bal = balance.get("A");
balance.put("A", bal + 1000);
System.out.println("A"s new balance: " + balance.get("A"));
}
}
Using the elements() or the values() method to get the set of all the values in the hash table
public Enumeration elements()
public Collection values()
value3 : null value2 : null value1 : null [value3, value2, value1]