View Single Post
  #2 (permalink)  
Old 11-21-2007, 08:55 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Code:
import java.util.*; public class ExpTest { public static void main(String[] args) { Random seed = new Random(); int limit = 100; String domain = "abcdefghizklmnopqrstuvwxyz"; // Arrange to save a random value for later lookup. String randomValue = null; int size = 10; int randomIndex = seed.nextInt(size); Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>(); for(int j = 0; j < size; j ++) { Integer key = Integer.valueOf(seed.nextInt(limit)); int index = seed.nextInt(domain.length()); String value = String.valueOf(domain.charAt(index)); if(j == randomIndex) { randomValue = value; System.out.println("randomValue = " + randomValue); } hashTable.put(key, value); } // Check keySet and entrySet. Set<Integer> keySet = hashTable.keySet(); System.out.println("keySet = " + keySet); Set<Map.Entry<Integer, String>> entrySet = hashTable.entrySet(); System.out.println("entrySet = " + entrySet); // Find the key corresponding to each occurrence of randomValue. Enumeration keys = hashTable.keys(); while(keys.hasMoreElements()) { Integer key = (Integer)keys.nextElement(); String value = (String)hashTable.get(key); if(value.equals(randomValue)) { System.out.printf("Found key: %d for randomValue: %s%n", ((Integer)key).intValue(), randomValue); } } } }
Reply With Quote