2012-10-24 2 views
0

내가 int[] array = {1, 2, 3}이 있고 아래 값으로 hashmap을 초기화하려는 경우 더 좋은 방법이 있습니까? 초기화기존 값이있는 hashmap 초기화?

Map<Integer,Boolean> map = new HashMap<Integer,Boolean>(); 
      map.put(1,false); 
      map.put(2,false); 
      map.put(3,false); 

답변

7
for (int i: array) { 
    map.put(i, false); 
} 
1

또 다른 방법은 다음과 같습니다

Map<Integer,Boolean> map = new HashMap<Integer, Boolean>() { 
          { 
           put(1,false); 
           put(2,false); 
           put(3,false); 
          } 
+2

이 생성 이 클래스는 HashMap의 익명 하위 클래스이며 상황에 따라 다를 수도 있고 그렇지 않을 수도 있습니다. 최소한 비용/단점을 이해하지 않고는 권장하지 않습니다. –

1

당신이 Guava를 사용하는 경우,

ImmutableMap.of(1, false, 2, false, 3, false); 

또는

ImmutableMap.builder().put(1, false).put(2, false).put(3, false).build()