2014년 6월 11일 수요일

[오라클자바커뮤니티 자바교육]자바자료구조[Map,TreeMap, SortedMap], Map의 키정렬,JAVA HASHMAP. SORTEDMAP

[오라클자바커뮤니티 자바교육]자바자료구조[Map,TreeMap, SortedMap], Map의 키정렬,JAVA HASHMAP. SORTEDMAP

Map은 key, value쌍으로 자료를 가지고 있는 자료구조 인터페이스이다.
Map중 key값이 정렬된 것이 SortedMap 인터페이스인데 이를 구현한것이 TreeMap이다.

아래 예제를 보자.

package onj;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class JCFTest {
public static void main(String[] args) {
SortedMap<Integer, String> sm = new TreeMap<Integer, String>();

sm.put(new Integer(3), "Three");
sm.put(new Integer(1), "One");
sm.put(new Integer(2), "Two");

//-----------------------------------------------------
Set s = sm.entrySet();
// Using iterator in SortedMap
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);
}
//-----------------------------------------------------

System.out.println("=========================================");

for (Map.Entry<Integer, String> entry : sm.entrySet()) {
System.out.println("Key: " + entry.getKey() + "-"
+ entry.getValue());
}
}
}


[결과]


Key :1  value :One
Key :2  value :Two
Key :3  value :Three
=========================================
Key: 1-One
Key: 2-Two
Key: 3-Three

댓글 없음:

댓글 쓰기