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的]
爲循環內的每個學生創建一個新的ArrayList。看來你正在重複使用並追加到同一個數組列表中。 – yogidilip
這幾乎是你的解決方案 –