user6702272 - 1 year ago 34
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();

...
... //Bunch of words
...

//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);
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!

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.