爪哇哈希映射的ArrayList
问题描述:
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
与ID
从HashMap
然后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
谢谢,这工作。 –
为循环内的每个学生创建一个新的ArrayList。看来你正在重复使用并追加到同一个数组列表中。 – yogidilip
这几乎是你的解决方案 –