开发者

Android: Error java.lang.IndexOutOfBoundsException Invalid Location

I have this method below which generates random number based on the size of my JSON Entries and each number may only come once. I cast the method 3 times, because I need to generate 3 random number which should be different between each other.

Sometimes it works, but sometimes it gives me this error on the logcat: Error java.lang.IndexOutOfBoundsException Invalid Location and that makes my app crashed.

Can anybody help me to solve my problem? Thx!

          int max = prjcts.size();
          List<Integer> indices = new ArrayList<Integer>(max);
          for(i开发者_如何学Cnt c = 1; c < max; ++c)
          {
              indices.add(c);
          }

          int arrIndex = (int)((double)indices.size() * Math.random());
          int randomIndex1 = indices.get(arrIndex);
          indices.remove(arrIndex);


          int randomIndex2 = indices.get(arrIndex);
          indices.remove(arrIndex);


          int randomIndex3 = indices.get(arrIndex);
          indices.remove(arrIndex);

@KPBird: So I change my code like what you told me to, but it still gives me errors soemtime: Am I missing something?

Random r = new Random();
  int arrIndex = r.nextInt(indices.size());
  int randomIndex1 = indices.get(arrIndex);
  indices.remove(arrIndex);


  int randomIndex2 = indices.get(arrIndex);
  indices.remove(arrIndex);


  int randomIndex3 = indices.get(arrIndex);
  indices.remove(arrIndex);


The problem is that indices.remove(...) removes the entry from the list and decreases the size of the list by 1 each time it's called. The other problem seems to be that you are attempting to get the same array index for each randomIndexX which doesn't really make any sense.

Edit: Complete example based on my comment below. This prints out the numbers 1 to N (inclusive) in random order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomX {  

  public static void main(String[] args) {
    int start = 1;
    int n = 10;
    List<Integer> numbers = new ArrayList<Integer>();

    for (int i = start; i <= n; i++) {
      numbers.add(i);
    }

    Collections.shuffle(numbers);

    for (int i = 0; i < n; i++) {
      System.out.println(numbers.get(i));
    }
  }

}


indices.size() * Math.random() can possibly return the size of the list. Which is one more than the last index.

So you should use indices.size() - 1 as a maximum value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜