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,test1,test],10 = [test3,test2,test1,test],11 = [test3,test2,test1,test1,test]}]
我试图将其指定为每个ID,因此,如果某人输入ID" 10 test" 10 test2" 100 test3",只有10个= [test2,test]和100 = [test3]
您需要从HashMap
获得现有的ArrayList
,然后使用add
,然后CC_4如下所示(遵循注释(:
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