zee*_*y23 1 java loops arraylist
我需要在while循环中创建一个Arraylist,其名称也基于循环中的变量.这就是我所拥有的:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
Run Code Online (Sandbox Code Playgroud)
变量truster在扫描时会出现多次,因此if语句试图检查arraylist是否已经存在.不过,我想我可能已经做到了这一点.
谢谢你的帮助!
将ArrayLists存储在Map中:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Run Code Online (Sandbox Code Playgroud)
请注意使用泛型(位<>)来定义List和Map可以包含的Object类型.
您可以访问存储在Map使用中的值listMap.get(listname);