简体   繁体   中英

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. 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.

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.

Reflection is not usually a good solution. Maybe use a Map instead of named 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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