2017-12-05 16 views
1

I가 내가 특정 키의 목록을 뽑아 특정 인덱스에 값을 추가 한 다음에 그것을 다시 넣고 싶은 TreeMap<String, List<Double> TreeMap. 아래 코드의시List.set

는 트리 맵에는 다음이 포함

{specificKey=[0,0,0], specificKey2=[0,0,0], specificKey3=[0,0,0]}

나는 인덱스 0 specificKey에 값을 추가 할, 그래서 여기에 {specificKey=[777,0,0], specificKey2=[0,0,0], specificKey3=[0,0,0]}

는 잘못된 코드입니다 .. .

if (myMap.containsKey(specificKey){ 
    List<Double> doubleList = myMap.get(specificKey); 
    doubleList.set(0, someValue); 
    myMap.put(specificKey, doubleList); 
} 

대신, 무슨 일이다 {specificKey=[777,0,0], specificKey2=[777,0,0], specificKey3=[777,0,0]}

myMap.get (specificKey)을 사용하여 정확한 List를 추출 할 때 왜 이런 현상이 발생합니까? 그리고 내가 필요한 것을 성취하는 방법에 대한 아이디어가 있습니까?

답변

3

모든 것을 올바르게하고 있습니다. 또한 목록이 이미 있으므로 myMap.put(specificKey, doubleList)을 삭제할 수 있습니다.

시나리오에서 이러한 이유는 TreeMap을 채울 때 만든 List<Double>의 동일한 인스턴스를 세 개의 키가 모두 참조하기 때문입니다. 이 문제를 해결하기 위해 각 키에 대한 새로운 목록을 삽입 할 코드를 변경 : 동일한 목록 개체의 세 가지 인스턴스와지도를 채운

myMap.put(specificKey1, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0)))); 
myMap.put(specificKey2, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0)))); 
myMap.put(specificKey3, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0)))); 
... 
if (myMap.containsKey(specificKey1){ 
    myMap.get(specificKey1).set(0, someValue); 
} 
2

. 세 가지 별개 목록을 만들어야합니다. 예 :

TreeMap<String, List<Double>> myMap = new TreeMap<>(); 
myMap.put(specificKey, Arrays.asList(0.0, 0.0, 0.0)); 
myMap.put(specificKey2, Arrays.asList(0.0, 0.0, 0.0)); 
myMap.put(specificKey3, Arrays.asList(0.0, 0.0, 0.0));