Java实现从Integer数组中随机获取非空元素对应索引的问题
问题解决方法
你需要用循环结构实现「抽到空索引就重试」的逻辑,不需要在else分支返回空值,修改后的实现如下:
// Random实例作为类成员变量,避免每次调用重新生成种子降低随机性 private Random random = new Random(); public int getRandomPosition(){ // 死循环反复生成索引,直到符合条件直接返回 while (true) { int index = random.nextInt(2 * numberOfCardPairs); if (myArray[index] != null) { return index; } } }
补充说明
- 不要每次调用方法都创建新的
Random实例,重复创建会导致生成的随机数序列重复,随机性不符合预期,放到类的成员变量位置一次创建多次使用即可。 - 注意你原代码中写的
number0fCardPairs,确认变量名里是数字0还是字母O,避免拼写错误导致编译失败。 - 如果存在数组全为空的场景,可以先提前校验避免死循环:
public int getRandomPosition(){ // 提前校验数组是否还有非空元素 boolean hasValidElement = false; for (Integer item : myArray) { if (item != null) { hasValidElement = true; break; } } if (!hasValidElement) { // 这里可以选抛异常,或者返回-1作为约定的错误标识,调用方自行判断处理 throw new IllegalStateException("数组中已无非空元素"); } while (true) { int index = random.nextInt(2 * numberOfCardPairs); if (myArray[index] != null) { return index; } } }
内容的提问来源于stack exchange,提问作者vabasda
相关产品推荐
相关产品推荐

