2013년 1월 14일 월요일

해쉬테이블

package soul;




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 hTable = new 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);

}





}



}

댓글 없음:

댓글 쓰기

국정원의 댓글 공작을 지탄합니다.

대학원생의 투고 지도 ④ (완결) — 논문의 수준이란 무엇인가: 사다리와 사분위, 첫 논문 전략

완결편이다. "논문 수준"이라는 말을 해부하고, 에듀테크 석사생의 첫 논문 전략으로 마친다. 학위논문과 학술지 논문은 다른 장르다 먼저 가장 흔한 혼동부터. 학위논문(thesis)은 "내가 연구를 수행할 줄 안다...