user6702272 user6702272 - 3 months ago 9
Java Question

For-loop only doing half the work I want it to, why?

While working on my android project I needed a bunch of random words, at first I generated words starting on a specific letter (a,b,c,...), Then I thought I would rather make a quick little helper that would make my work faster done, than manually type and sort them, so I open Eclipse and made this:

public static void main(String[] args) {

words = new ArrayList();
randomWords = new ArrayList();


words.add("add");
words.add("applied");
words.add("deck");
words.add("demonstrator");
words.add("disability");
words.add("dip");
...
... //Bunch of words
...
words.add("kneel");
words.add("knowledge");
words.add("kid");


//260 words in total

System.out.println("word size " + words.size());



for (int i = 0; i < words.size(); i++) {


Random random = new Random();
int randomNumber = random.nextInt(words.size());

String string = words.get(randomNumber);
randomWords.add(string);
System.out.println("words.add(\"" + string + "\");");
words.remove(randomNumber);

}

System.out.println("randomWord size " + randomWords.size());


This line is giving me a number of 260.

System.out.println("word size " + words.size());


After running the for-loop I end up with 130 items added in randomWord ArrayList and other half still being in the words ArrayList.




What did I miss and is wrong? Also, what exactly is happening in my code?

Any help is greatly appreciated!

Answer
for (int i = 0; i < words.size(); i++) {

That's your problem. That calls words.size() every iteration, not just once. After 130 calls, i is 130, and words.size() returns 130 (since it's shrunk so much), so it quits early.

As has been pointed out, just setting that to 260 won't work either. You need to make the condition equivalent to "While the list still has elements": A while loop could work for that, or (super-hacky, don't do this), a for loop with no increment.