Learning
Learning

Reputation: 89

java - Storing String sequence in arraylist

I am trying to create a list using the code below, that stores random binary strings. But everytime I print the string elements of list, all the string elements that are printed are the same. ex- 101 101 101 101. How do I make it work?

ArrayList<String[]> coded = new ArrayList<String[]>();
Random rand = new Random();

for(int j=0; j<4;j++){  

    for (int i=0; i<3;i++){  
        rand1 = (rand.nextInt(4)+0)%2;
        x1[i]= "" + rand1;
    }  
    coded.add(x1);
}  

Upvotes: 1

Views: 368

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

You have only declared one x1 array (somewhere), so in essence you're just adding a bunch of references to the same array to the list. The array will contain the values that were inserted during the last iteration.

Declare the array inside the loop to fix the issue.

for (int j=0; j<4; j++){  
    String[] x1 = new String[3];

    for (int i=0; i<3; i++){  
        rand1 = (rand.nextInt(4) + 0) % 2;
        x1[i]= "" + rand1;
    }  

    coded.add(x1);
}  

Upvotes: 1

Related Questions