Key-Value 방식의 데이터 저장과 HashMap<K,V> 클래스
Key는 지표이므로 중복될 수 없다. 반면 Key만 다르면 Value는 중복되어도 상관없다.
Map<K,V>를 구현하는 대표 클래스로 HashMap<K,V>와 TreeMap<K,V>가 있다.
둘의 가장 큰 차이점은 트리 자료구조를 기반으로 구현된
TreeMap<K,V>는 정렬 상태를 유지한다는데 있다. 물론 정렬의 대상은 Value가 아니라 Key이다
먼저 HashMap<K,V>사용의 예를 살펴보자.
HashMap<Integer, String> map = new HashMap<>();
map.put(45,"Brown");
map.put(37,"James");
map.put(23,"Martin");
System.out.println("23번 : "+map.get(23));
System.out.println("37번 : "+map.get(37));
System.out.println("45번 : "+map.get(45));
System.out.println();
map.remove(37);
System.out.println("37번 : "+map.get(37));
----------------------------------------------------------------------
23번 : Martin
37번 : James
45번 : Brown
37번 : null
예제의 다음 문장에서 보이듯이 Key도 Value도 인스턴스이어야 한다.
HashMap<Integer, String> map = new HashMap<>();
--------------------------------------------------------------------
다만 예제에서는 Key가 Integer이므로 저장 참조 그리고 삭제의 과정에서 Key에 대한
오토 박싱과 오토 언박싱이 진행되어서 int형 정수가 key로 보였을 뿐이다.
HashMap<K,V> 순차적 접근 방법
Key는 중복이 안된다고 하였다
그러면 Key는 list,Set 중에서 어떤 인스턴스로 해야할까?
당연히 중복을 허용하지 않는 Set이 어울린다.
----------------------------------------------------------------------
HashMap<K,V> 클래스는 Iterable<T> 인터페이스를 구현하지 않으니(Collection을 상속X)
for - each문을 통해서 혹은 '반복자'를 얻어서 순차적 접근을 진행할 수 없다.
대신에 Map<K,V>에는 다음 메소드가 존재한다
-----------------------------------------------------------------------
public Set<K> ketSet()
-----------------------------------------------------------------------
이 메소드는Set<E>를 구현하는 컬렉션 인스턴스를 생성하고 모든 Key를 담아서 반환한다.
따라서 이 메소드를 통해 다음 예제와 같이 모든 Key를 따로 모으고 이를통한 순차적 접근을
진행할 수 있다.
HashMap<Integer, String> map = new HashMap<>();
map.put(45,"Brown");
map.put(37,"James");
map.put(23,"Martin");
Set<Integer> ks = map.keySet();
for(Integer n : ks)
System.out.print(n.toString() + '\t');
System.out.println();
for(Integer n :ks)
System.out.print(map.get(n).toString()+'\t');
System.out.println();
for(Iterator<Integer> itr = ks.iterator(); itr.hasNext();)
System.out.print(map.get(itr.next())+'t');
System.out.println();
----------------------------------------------------------------------
37 23 45
James Martin Brown
James Martin Brown
TreeMap<K,V> 순차적 접근 방법
HashSet<E>이 해쉬 알고리즘으로 구현되어 있듯이 HashMap<K,V>역시 해쉬 알고리즘 기반이다.
TreeSet<E>이 트리 알고리즘기 구현되어 있으니 TreeSet<K,V>역시 트리 알고리즘 기반이다.
TreeMap<Integer, String> map = new TreeMap<>();
map.put(45,"Brown");
map.put(37,"James");
map.put(23,"Martin");
Set<Integer> ks = map.keySet();
for(Integer n : ks)
System.out.print(n.toString() + '\t');
System.out.println();
for(Integer n :ks)
System.out.print(map.get(n).toString()+'\t');
System.out.println();
for(Iterator<Integer> itr = ks.iterator(); itr.hasNext();)
System.out.print(map.get(itr.next())+'t');
System.out.println();
-----------------------------------------------------------------------
23 37 45
Martin James Brown
Martin James Brown
----------------------------------------------------------------------
실행 결과 Key에 해당하는 나이 정보가 오름차순으로 출력되었다.
이렇듯 대상 컬렉션 인스턴스에
따라서 반환되는 반복자의 성격은 달라진다.
Comparator를 이용해 내림차순으로 정렬해보기
class IntegerComparator implements Comparator<Integer>{
public int compare(Integer s1, Integer s2){
return s2.intValue()- s1.intValue();
}
}
public class ComparatorTreeMap {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>(new IntegerComparator());
map.put(45,"Brown");
map.put(37,"James");
map.put(23,"Martin");
Set<Integer> ks = map.keySet();
for(Integer n : ks)
System.out.print(n.toString() + '\t');
System.out.println();
for(Integer n :ks)
System.out.print(map.get(n).toString()+'\t');
System.out.println();
for(Iterator<Integer> itr = ks.iterator(); itr.hasNext();)
System.out.print(map.get(itr.next())+'t');
System.out.println();
-----------------------------------------------------------------------
45 37 23
Brown James Martin
Brown James Martin