简体   繁体   English

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

[英]How can I apply the name of a field to an ArrayList and then add something to that ArrayList

Well, I want to import the name of a field from a CSV file and then add all the data after the name of the file into the corresponding ArrayList.好吧,我想从CSV文件中导入一个字段的名称,然后将文件名后面的所有数据添加到对应的ArrayList中。 I know how I can ask the class if that Field exists and if it is present but then I don't know how I can then apply the name of the field and use.add to add an element to the Array Pls, help it's for my School project.我知道如何询问 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);
    }

I expect that I can use the first word of the CSV file and convert it to the name of the array in the class and then add all of the elements of the CSV file into the array.我希望我可以使用 CSV 文件的第一个字并将其转换为 class 中的数组名称,然后将 CSV 文件的所有元素添加到数组中。

Reflection is not usually a good solution.反射通常不是一个好的解决方案。 Maybe use a Map instead of named arrays.也许使用 Map 而不是命名为 arrays。

var dataByName = new HashMap<String, List<String>>();

Then, after you read and split a line from your file.然后,在您从文件中读取并拆分一行之后。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM