JAVA Basic 강의자료] 헤쉬테이블(HashTable) 사용 예

 

JAVA Basic 강의자료] 헤쉬테이블(HashTable) 사용 예

 

 

 

 

 

실무개발자를위한 실무교육 전문교육센터학원
www.oraclejava.co.kr에 오시면 보다 다양한 강좌를 보실 수 있습니다.

 

 

 

헤쉬테이블(HashTable) 사용 예(1)

 

<소스코드>

 

import java.util.Hashtable;
public class HashtableTest {
 public static void main(String[] args) {
  Hashtable hashtable = new Hashtable();
  
        //1. hashtable에 객체의 삽입 
  hashtable.put("Name", new String("홍길동"));
  hashtable.put("Age", new Integer(27));
  hashtable.put("Tel", new String("02-1111-2222"));
  hashtable.put("Handphone", new String("017-777-9999"));
  hashtable.put("Etc", new String("I'm a boy"));
  
        //키 값을 이용하여 객체 추출
  String name = (String)hashtable.get("Name");
  if (name != null) {
   System.out.println("Name = " + name);
  }
 
  Integer age = (Integer)hashtable.get("Age");
  if (age != null) {
   System.out.println("Age = " + age.intValue());
  }
   }
}


 

 

헤쉬테이블(HashTable)  사용예(2)

 

 

<소스코드>

 

import java.util.*;
public class StudentHashtableTest {

 public static void main(String[] args) {
  Hashtable table=new Hashtable();
  table.put("1",new Student("Jee",1,"Seoul"));//0
  table.clear();//모두 제거

  table.put("2",new Student("Gong",2,"Seoul"));//1
  table.put("3",new Student("Song",3,"Seoul"));//2
  table.put("4",new Student("Lee",4,"Koyang"));//3
  table.put("4",new Student("Lee",4,"Koyang"));//3과 중복x
  System.out.println(table.size());
  System.out.println(table.containsKey("4"));
  
         table.remove("3");
  Student stu=(Student)table.get("2");//key
  System.out.println(stu.getId()+"  "+stu.getName()+"  "+stu.getAddr());
  //모든 elements 출력하기
  //Set set=table.keySet();//Map을 참고
  Enumeration enums=table.keys();
  while(enums.hasMoreElements()){
       String key=(String)enums.nextElement() ;//핵심
       Student stus=(Student)table.get(key);
       System.out.println(stus.getId()+"  "+stus.getName()+"                               "+stus.getAddr());
  }
 }
}

 

+ Recent posts