2016-05-12 3 views
1

インデックス付きの別のマップに全体のマップを保存したい。 私のコードは以下の通りです:別のインデックスマップで1つのマップを保存するJava

ここ
HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>(); 
Map<String, String> mapCust = new HashMap<String, String>(); 

for (int i = 0; i < 10; i++) { 
    mapCust.put("fname", fname); 
    mapCust.put("lname", lname); 
    mapCust.put("phone1", phone1); 
    mapCust.put("phone2", phone2); 

    custMap.put(i, mapCust); 
} 

私は合計2つの地図custMapmapCustを持っています。 custMapは、インデックス付きマップとして、mapCustの10個のサブマップが必要です。

ここで、fname、lname、phone1、およびphone2は、マップmapCustごとに異なります。

今のところ、すべての10のサブマップで最後の値がmapCustのような同じ値のすべての10のサブマップがあります。

+1

あなたは常に 'mapCust'の同じインスタンスで作業しているからです。ループの開始時に 'mapCust'を再割り当てしたいかもしれません – SomeJavaGuy

答えて

5

HashMapは参照を保持するので、各キーに割り当てる新しいオブジェクトを作成する必要があります。

HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>(); 

for (int i = 0; i < 10; i++) { 
    Map<String, String> mapCust = new HashMap<String, String>(); // move this line inside the loop 
    mapCust.put("fname", fname); 
    mapCust.put("lname", lname); 
    mapCust.put("phone1", phone1); 
    mapCust.put("phone2", phone2); 

    custMap.put(i, mapCust); 
} 
2

あなたは何度も何度もmapCustの同じインスタンスを使用していた

以前
HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer,Map<String, String>>(); 

for (int i = 0; i < 10; i++) { 
Map<String, String> mapCust = new HashMap<String, String>(); 
mapCust.put("fname", fname); 
mapCust.put("lname", lname); 
mapCust.put("phone1", phone1); 
mapCust.put("phone2", phone2); 
custMap.put(i, mapCust); 
} 

を繰り返すHashMap毎回の新しいインスタンスを作成します。

関連する問題