1

I am having a problem with adding new elements to an ArrayList , I will show you my problem :

ArrayList<ArrayList<String>> arr1= new ArrayList<ArrayList<String>>();
ArrayList<String> arr2= new ArrayList<String>();

So I am adding new elements from a text file , spliting it line by line , then word by word , example : we suppose my text file contains :

a,b,c,d
e,f,g,h
i,j,k,l

What I need is to put each word in arr2 , then i put arr2 into arr1 with the following code :

while ((line = file.readLine()) != null) {
            String[] words = line.split("\\,");
            if (arr2.isEmpty()) {
                for (int ae = 0; ae < words.length; ae++) {
                    arr2.add(ae, words[ae]);
                }
                arr1.add(arr2);
            } else {
                for (int ae = 0; ae < words.length; ae++) {
                    arr2.set(ae, words[ae]);
                }
                arr1.add(arr2);                    
            }
        }
        file.close();

So what I need is :[[a,b,c,d],[e,f,g,h],[i,j,k,l]] but I get : [[i,j,k,l],[i,j,k,l],[i,j,k,l]]

Any solution please?!

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
  • 1
    You are adding same list (arr2) 3 times. You need to fill and add *separate* (new) lists, not re-*set* same one. – Pshemo Mar 10 '18 at 19:20
  • 1
    you should create a new `ArrayList arr2= new ArrayList();` every time – dehasi Mar 10 '18 at 19:20

1 Answers1

2

In java it deals with references, So you have to create new arr2 every time you read the line because when you add arr2 to arr1 it still hold the reference of arr2 too, So every change you are making on arr2 affects arrays inside arr1 + the array arr2 that is going to be added to arr1 (They are all the same array).

A kind of solution is to declare arr2 inside the while loop like this ArrayList<String> arr2= new ArrayList<String>(); as @dehasi said in the comments,

while ((line = file.readLine()) != null) {
        ArrayList<String> arr2= new ArrayList<String>();
        String[] words = line.split("\\,");
        for (int ae = 0; ae < words.length; ae++) {
            arr2.add(words[ae]);
        }
        arr1.add(arr2);

    }
    file.close();

Hope it helps.

Amr Adel
  • 574
  • 1
  • 7
  • 18