import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class WhatIsHashTable {
class DataStorage {
int key;
Object data;
public DataStorage(int key, Object data) {
this.key = key;
this.data = data;
}
}
DataStorage[] table = new DataStorage[100];
int n = 0;
public void add(int key, Object data) {
table[n++] = new DataStorage(key, data);
}
public Object search(int key) {
int i;
i = 0;
while (i < n) {
if (table[i].key == key)
return (table[i].data);
i++;
}
return null;
}
public static void main(String args[]) {
WhatIsHashTable ls8 = new WhatIsHashTable();
ls8.add(8, "eight");
ls8.add(1, "one");
ls8.add(2, "two");
ls8.add(3, "three");
String x;
x = (String) ls8.search(3);
if (x != null) {
System.out.println("Searched data = " + x);
} else {
System.err.println("data Not found");
}
System.out.println("//-----------");
//-----------
// HASHTABLE
// 출처 http://www.easywayserver.com/blog/java-hashtable-example/
/*
* Hashtable class is part of java.util package. Hashtable class can add key and value put(key, value) pair elements. Hashtable do not permit null key and value. But Hashtable is synchronized. Hashtable class return ordered entry as entered.
Hashtable extends Dictionary class and implements Map interface. Key and value of Hashtable can get by Set Interface and Map interface through Iterator and Enumeration interface.
Hashtable example give a method, how to use Hashtable in java
*/
Hashtable
// adding or set items in Hashtable by put method key and value pair
hTable.put(new Integer(2), "Two");
hTable.put(new Integer(1), "One");
hTable.put(new Integer(4), "Four");
hTable.put(new Integer(3), "Three");
hTable.put(new Integer(5), "Five");
// Get Hashtable Enumeration to get key and value
Enumeration em = hTable.keys();
while (em.hasMoreElements()) {
// nextElement is used to get key of Hashtable
int key = (Integer) em.nextElement();
// get is used to get value of key in Hashtable
String value = (String) hTable.get(key);
System.out.println("Key :" + key + " value :" + value);
}
System.out.println("//------------");
//-------------
Set s =hTable.entrySet();
Iterator i=s.iterator();
while(i.hasNext())
{
Map.Entry m=(Map.Entry)i.next();
int key = (Integer)m.getKey();
String value=(String)m.getValue();
System.out.println("Key :"+key+" value :"+value);
}
}
}
댓글 없음:
댓글 쓰기
국정원의 댓글 공작을 지탄합니다.