2021年1月27日星期三

ArrayList stores only the last element

What I tried to achieve is to separate the text input into groups when there's an empty line. The way I wanted to achieve this is by adding the lines to ArrayList< String > temp until there's an empty line. After that I added temp to ArrayList<ArrayList< String >> group. But It seems like It only adds the last temp values to group. I can't see why. Here's the code:

public static void main(String... args) throws IOException {      List<String> data = new ArrayList<>();      File f = new File("input6.txt");        try (Scanner sc = new Scanner(f)) {          while (sc.hasNext()) {              data.add(sc.nextLine());          }      } catch(FileNotFoundException e) {          e.printStackTrace();      }            List<List<String>> group = new ArrayList<>();      List<String> temp = new ArrayList<>();            for (String line : data) {          temp.add(line);          if (line.trim().isEmpty()) {                group.add(temp);              temp.clear();          }      }  }  
https://stackoverflow.com/questions/65908277/arraylist-stores-only-the-last-element January 27, 2021 at 03:50AM

没有评论:

发表评论