SSISO Community

시소당

Map(HashMap, TreeMap, Hashtable)

  #  Collection  #

◎  Map은  key와  value를  가진  집합이며,  중복을  허용하지  않는다.
◎  즉,  한개의  key에  한개의  value가  매칭된다.
◎  java.util  패키지에  여러  집합들을  사용하기  위한  여러  interface와  class  들이  정의되어  있다.

#  HashMap  #

◎  HashMap은  Map  interface를  implements  한  클래스로서  중복을  허용하지  않는다.
◎  Map의  특징인  key와  value의  쌍으로  이루어지며,  key  또는  value  값으로써  null을  허용한다.
◎  아래의  예는  HashMap을  사용한  간단한  예제이다.  

public  class  HashMapTest
{
public  static  void  main(String  argv[])
{
HashMap  hm  =  new  HashMap();
System.out.println(hm.put("aaa",  "111"));
System.out.println(hm.put("bbb",  "222"));
System.out.println(hm.put("aaa",  "444"));
System.out.println(hm.put("ccc",  "333"));
System.out.println(hm.put("ccc",  null));

System.out.println("HashMap  size  :  "  +  hm.size());

Set  set  =  hm.keySet();
Object  []hmKeys  =  set.toArray();
for(int  i  =  0;  i  <  hmKeys.length;  i++)
{
String  key  =  (String)hmKeys[i];
System.out.print(key);
System.out.print("  -  ");
System.out.println((String)hm.get(key));
}
}
}
/**
실행:java  HashMapTest
결과:
null
null
111
null
333
HashMap  size  :  3
ccc  -  null
bbb  -  222
aaa  -  444
*/
  

  

#  TreeMap  #


◎  TreeMap역시  중복을  허용하지  않으며,  key와  value의  쌍으로  이루어져  있다.
◎  HashMap과  다른  점은  SortedMap을  implements  하였으므로,  key  값들에  대한  정렬이  이루어진다는
          점이다.
◎  아래의  예는  TreeMap을  사용하여  각  요소가  몇몇  이나  나왔는지  알아보는  간단한  예제이다.

  

  
import  java.util.*;

public  class  Freq  {
private  static  final  Integer  ONE  =  new  Integer(1);

public  static  void  main(String  args[])  {
Map  m  =  new  TreeMap();

//  Initialize  frequency  table  from  command  line
for  (int  i=0;  i  <  args.length;  i++)  {
Integer  freq  =  (Integer)  m.get(args[i]);
m.put(args[i],  (freq==null  ?  ONE  :
new  Integer(freq.intValue()  +  1)));
}

System.out.println(m.size()+"  distinct  words  detected:");
System.out.println(m);
}
}
/**
실행:java  Freq  if  it  is  to  be  it  is  up  to  me  to  delegate
결과:
8  distinct  words  detected:
{be=1,  delegate=1,  if=1,  is=2,  it=2,  me=1,  to=3,  up=1}
*/

  

  

#  Hashtable  #


◎  Hashtable  Map  interface를  implements  한  클래스로서  중복을  허용하지  않는다.
◎Map의  특징인  key와  value의  쌍으로  이루어지며,  key  또는  value  값으로써  null을  허용하지  않는다.
        (HashMap과의  차이점)
아래의  예는  HashTable을  사용한  간단한  예제이다.

  
public  class  HashtableTest
{
public  static  void  main(String  argv[])
{
Hashtable  ht  =  new  Hashtable();
System.out.println(ht.put("aaa",  "111"));
System.out.println(ht.put("bbb",  "222"));
System.out.println(ht.put("aaa",  "444"));
System.out.println(ht.put("ccc",  "333"));

System.out.println("Hashtable  size  :  "  +  ht.size());

System.out.println("aaa  value  :  "  +  (String)ht.get("aaa");

}
}
/**
실행:java  HashMapTest
결과:
null
null
111
null
Hashtable  size  :  3
aaa  value  :  444
*/  

[자바전문가과정  문의  =  http://www.lesson-web.com/prom/java_main.htm]

1171 view

4.0 stars