[英]How can I apply the name of a field to an ArrayList and then add something to that ArrayList
好吧,我想从CSV文件中导入一个字段的名称,然后将文件名后面的所有数据添加到对应的ArrayList中。 我知道如何询问 class 该字段是否存在以及是否存在,但我不知道如何应用该字段的名称并 use.add 将元素添加到数组中请帮助我的学校项目。
try {
scanner = new Scanner(new FileInputStream(filename), "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] splitLines = line.split(",");
Field field = Main.class.getField("splitLines[0]");
if(ArrayList.class.isAssignableFrom(field.getType())){
for (int i = 0; i < splitLines.length; i++) {
/*this is where I want to add all of the Data to the
corresponding array*/
}
}
}
scanner.close();
} catch (FileNotFoundException | NoSuchFieldException e) {
System.out.println("File not found " + filename);
}
我希望我可以使用 CSV 文件的第一个字并将其转换为 class 中的数组名称,然后将 CSV 文件的所有元素添加到数组中。
反射通常不是一个好的解决方案。 也许使用 Map 而不是命名为 arrays。
var dataByName = new HashMap<String, List<String>>();
然后,在您从文件中读取并拆分一行之后。
var dataList = new ArrayList<String>();
for (int s = 1; s < splitLines.length; s++) {
dataList.add(splitLines[s]);
}
dataByName.put(splitLines[0], dataList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.