자바/자바 입문 공부일지

자바 기초 공부 일지 42. 컬렉션 클래스 (5) 맵HashMap<K, V>

Tomitom 2022. 11. 3. 11:30
반응형

 

HashMap<K, V>은 두 개의 자료가 하나의 요소를 구성하는 특성을 지닙니다. 

각 자료는 키key와 값value으로 구분됩니다. 

key는 실질적 데이터가 아니며, 실질적 데이터인 value를 찾기 위한 지표 역할을 합니다. 

 

key는 지표의 역할을 하기 때문에 중복이 되면 안 됩니다.

즉,키key의 중복은 불가능하지만 값value의 중복은 가능합니다. 

 

HashMap<K, V>은 key라는 지표가 있기 때문에 순서를 유지할 필요가 없으므로 배열 순서가 없습니다. 

 

아래의 예제를 살펴볼게요. 

 

public static void main(String[] args) {
   HashMap<Integer, String> map = new HashMap<>();
 
   // Key-Value 기반 데이터 저장
   map.put(45, "Brown");  // (key, value) 순으로 저장 
   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));
}

 

HashMap<K, V> 클래스는 Iterable<T> 인터페이스를 구현하지 않기 때문에

for-each문을 통해서, 혹은 ‘반복자’를 얻어서 순차적 접근을 진행할 수 없습니다. 

대신 다음 메소드 호출을 통해서 Key를 따로 모아 놓은 컬렉션 인스턴스를 얻을 수 있습니다.

그리고 이때 반환된 컬렉션 인스턴스를 대상으로 반복자를 얻을 수 있습니다. = Key의 Set 값들을 얻을 수 있습니다. 

 public Set<K> keySet()


 

HashMap해쉬 맵에 순차적으로 접근하는 방법에 대해 아래의 코드와 주석으로 확인해볼게요. 

 

public static void main(String[] args) {
   HashMap<Integer, String> map = new HashMap<>();
   map.put(45, "Brown");
   map.put(37, "James");
   map.put(23, "Martin");

   // Key만 담고 있는 컬렉션 인스턴스 생성
   Set<Integer> ks = map.keySet();

   // 전체 Key 출력 (for-each문 기반)
   for(Integer n : ks)
      System.out.print(n.toString() + '\t');
   System.out.println();

   // 전체 Value 출력 (for-each문 기반)
   for(Integer n : ks)
      System.out.print(map.get(n).toString() + '\t');
   System.out.println();

   // 전체 Value 출력 (반복자 기반)
   for(Iterator<Integer> itr = ks.iterator(); itr.hasNext(); )
      System.out.print(map.get(itr.next()) + '\t');
   System.out.println();
}

 

다음은 TreeMap에 순차적으로 접근하는 방법에 대해 아래 코드와 주석으로 확인해볼게요. 

 

public static void main(String[] args) {
   TreeMap<Integer, String> map = new TreeMap<>();
   map.put(45, "Brown");
   map.put(37, "James");
   map.put(23, "Martin");

   // Key만 담고 있는 컬렉션 인스턴스 생성
   Set<Integer> ks = map.keySet();

   // 전체 Key 출력 (for-each문 기반)
   for(Integer n : ks)
      System.out.print(n.toString() + '\t');
   System.out.println();

   // 전체 Value 출력 (for-each문 기반)
   for(Integer n : ks)
      System.out.print(map.get(n).toString() + '\t');
   System.out.println();

   // 전체 Value 출력 (반복자 기반)
   for(Iterator<Integer> itr = ks.iterator(); itr.hasNext(); )
      System.out.print(map.get(itr.next()) + '\t');
   System.out.println();
}

Tree 자료구조의 특성상 반복자가 정렬된 순서대로 key들에 접근을 하고 있습니다.

이렇듯 반복자의 접근 순서는 컬렉션 인스턴스(해쉬, 트리 등) 에 따라 달라질 수 있습니다. 

 


아래의 예시를 통해 한 번 더 확인을 할게요.

첫 번째로 내림차순의 정렬입니다. 

 

package day19;
import java.util.*;


class NumberComparator implements Comparator<Integer>{

	@Override
	public int compare(Integer o1, Integer o2) {
		
		//내림 차순으로 바꾸려면 객체 자신에게 비교 방법을 지정하는 법 : comparable
		return o2.intValue() - o1.intValue(); // intValue로 언박싱한 값. 
	}
	
}
public class TreeMap01 {

	public static void main(String[] args) {
		
		TreeMap<Integer, String> map = new TreeMap<>(new NumberComparator()); 
		
		map.put(11, "롱보우");
		map.put(7, "바스타드 소드");
		map.put(18,  "실버 원드"); 
		
		Set<Integer> ks = map.keySet(); 

		
		for(Integer n : ks) { 
			System.out.println(map.get(n));
			}
	}

}

 

이번에는 오름차순의 정렬입니다. 

 

package day19;
import java.util.*;


class NumberComparator implements Comparator<Integer>{

	@Override
	public int compare(Integer o1, Integer o2) {
		
		//내림 차순으로 바꾸려면 객체 자신에게 비교 방법을 지정하는 법 : comparable
		return o1.intValue() - o2.intValue(); // intValue로 언박싱한 값. 
	}
	
}
public class TreeMap01 {

	public static void main(String[] args) {
		
		TreeMap<Integer, String> map = new TreeMap<>(new NumberComparator()); 
		
		map.put(11, "롱보우");
		map.put(7, "바스타드 소드");
		map.put(18,  "실버 원드"); 
		
		Set<Integer> ks = map.keySet(); 

		
		for(Integer n : ks) { 
			System.out.println(map.get(n));
			}
	}

}

 

 

@Override
public int compare(Integer o1, Integer o2) {

//내림 차순으로 바꾸려면 객체 자신에게 비교 방법을 지정하는 법 : comparable
return o1.intValue() - o2.intValue(); // intValue로 언박싱한 값. 

 

 

이 부분의 차이점을 확인해주세요. 

 

반응형