Java Tutorial/Collections/Hashtable Basics

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Adding Key-Value Pairs

   <source lang="java">

public Object put(Object key, Object value)</source>



key3 : value3
key2 : value2
key1 : value1


Check if a particular key exists in Java Hashtable

   <source lang="java">

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

}</source>





Check if a particular value exists in Java Hashtable

   <source lang="java">

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

}</source>





Cloning Hash Tables

The Hashtable class provides its own implementation of the clone() method.



   <source lang="java">

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

}</source>



{key3=value3, key2=value2, key1=value1}


contains() and containsValue(): check to see if a specific value is found within the Hashtable

   <source lang="java">

public boolean contains(Object value) public boolean containsValue(Object value)</source>



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.



   <source lang="java">

public void putAll(Map map)</source>



{key6=value6, key5=value5, key4=value4, key3=value3, key2=value2, key1=value1}


Counting Word Occurrences with a hash table

   <source lang="java">

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

}</source>





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



   <source lang="java">

public Hashtable() public Hashtable(int initialCapacity) public Hashtable(int initialCapacity, float loadFactor)</source>





Displaying Hash Table Contents

The Hashtable class overrides the toString() method of the Object class



   <source lang="java">

public String toString()</source>



{key3=value3, key2=value2, key1=value1}


Fetching Keys and Values: the get() method

   <source lang="java">

public Object get(Object key)</source>



key3 : value3
key2 : value2
key1 : value1


Finding Elements

   <source lang="java">

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"));
 }

}</source>



true


Get all keys and elements from a hash table

   <source lang="java">

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

}</source>





Get Collection of Values from Hashtable

   <source lang="java">

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

}</source>





Get Set view of Keys from Hashtable

   <source lang="java">

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

  • /</source>





Getting elements (key-value pairs) from a Hashtable: the entrySet() method

   <source lang="java">

public Set entrySet()</source>



key3 : value3
key2 : value2
key1 : value1


Hashtable Immutability: to make the table read-only using Collections.unmodifiableMap(Map map)

   <source lang="java">

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

}</source>



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

   <source lang="java">

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

}</source>





Iterate through values of Java Hashtable

   <source lang="java">

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

}</source>





Remove all values from Java Hashtable

   <source lang="java">

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

}</source>





Remove value from Java Hashtable

   <source lang="java">

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

}</source>





Removing Key-Value Pairs: call the remove() method with the specific key as its argument

   <source lang="java">

public Object remove(Object key)</source>



{key3=value3, key2=value2}


Scan the content of a hashtable

   <source lang="java">

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

}</source>





Sizing Hash Tables

   <source lang="java">

public int size() public boolean isEmpty()</source>



false
3


Sort keys in an Hashtable

   <source lang="java">

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

}</source>





To get rid of all key-value pairs: call the clear() method

   <source lang="java">

public void clear()</source>



{}


To perform some operation on all keys: the keys() or keySet() methods

   <source lang="java">

public Enumeration keys() public Set keySet()</source>



key3 : value3
key2 : value2
key1 : value1
[key3, key2, key1]


Use iterators with a Hashtable.

   <source lang="java">

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"));
 }

}</source>





uses a generic Hashtable to store the names of bank depositors and their current balances

   <source lang="java">

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"));
 }

}</source>





Using the elements() or the values() method to get the set of all the values in the hash table

   <source lang="java">

public Enumeration elements() public Collection values()</source>



value3 : null
value2 : null
value1 : null
[value3, value2, value1]