1

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);
}  
3
  • Where do you declare x1? Do you have more than one array to add? Commented May 20, 2016 at 7:12
  • It would also be interesting to see your print method, just to confirm you are printing all the elements of the array and not just the first one, for example Commented May 20, 2016 at 7:25
  • The problem was i had declared the array x1 before the loop. It contained the elements added to it in the last iteration. So all the string arrays in the list had the same elements of x1. I declared the array inside the loop and it worked perfectly fine. Commented May 20, 2016 at 7:32

1 Answer 1

1

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);
}  
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I had declared the array before the loop and that was causing the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.