为了账号安全,请及时绑定邮箱和手机立即绑定

如何将字段名称应用于 ArrayList,然后向该 ArrayList 添加内容

如何将字段名称应用于 ArrayList,然后向该 ArrayList 添加内容

弑天下 2023-12-13 16:54:29
嗯,我想从CSV文件中导入一个字段的名称,然后将文件名后面的所有数据添加到相应的ArrayList中。我知道如何询问该类该字段是否存在以及是否存在,但我不知道如何应用该字段的名称并使用 .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 文件的第一个单词并将其转换为类中数组的名称,然后将 CSV 文件的所有元素添加到数组中。
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

反射通常不是一个好的解决方案。也许使用 Map 而不是命名数组。


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);


查看完整回答
反对 回复 2023-12-13
  • 1 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信