2017-05-04 96 views
1
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.HashMap; 
import java.util.List; 
import javax.swing.JOptionPane; 


public class HashMapDemo { 
public static double runProcess; 
public static int ID = 0; 
public static void processHashMap() { 
    HashMap < Integer, ArrayList <String>> students = new HashMap < >(); 
    List <String> arr = new ArrayList < > (100); 
    int x = 0; 
    while (ID != -1) { 
    String uData = JOptionPane.showInputDialog("Please enter your Student ID and Course Number (Seperated by a space) or enter -1 to view list: "); 
    String[] splitter = uData.split(" "); 
    ID = Integer.parseInt(splitter[0]); 
    arr.add(0, splitter[1]); 
    students.put(ID, (ArrayList <String>) arr); 
    x++; 
    } 
    System.out.println(Arrays.asList(students)); 

} 
public static void main(String[] args) { 
    processHashMap(); 
} 

} 

輸出是:[{-1 = [Test3的,Test2的,測試1,試驗],10 = [Test3的,Test2的,測試1,試驗],11 = [Test3的,Test2的,測試1,試驗] }]爪哇哈希映射的ArrayList

我試圖讓它被指定給每個ID,這樣如果有人輸入ID「10測試」「10測試2」「100測試3」只有10將是10 = [測試2,測試]和100 = [Test3的]

+2

爲循環內的每個學生創建一個新的ArrayList。看來你正在重複使用並追加到同一個數組列表中。 – yogidilip

+0

這幾乎是你的解決方案 –

回答

2

你需要讓現有ArrayListIDHashMap然後add給它的新元素,如下圖所示(後續評論):

String[] splitter = uData.split(" "); 
ID = Integer.parseInt(splitter[0]); 
ArrayList<String> studentsList = students.get(ID);//get the existing list from Map 
if(studentsList == null) {//if no list for the ID, then create one 
    studentsList= new ArrayList<>(); 
} 
studentsList.add(0, splitter[1]);//add to list 
students.put(ID, studentsList);//put the list inside map 
+0

謝謝,這工作。 –