从数组中移除随机元素并将其添加到另一个数组:数组越界错误。

huangapple go评论60阅读模式
英文:

Removing random element from array and adding it to another array: OutOfIndex bound error

问题

这段代码有什么问题?
我试图从一个ArrayList中随机选择一个元素并将其移动到另一个ArrayList中以创建一个排列。它一直给我越界错误。

int size = 10;
for (int i = 0; i < 10; i++) {
    int r = (int) (Math.random() * (size));
        
    random.remove(r);
    permutations.add(random.get(r));
    size--;
        
}

这段代码存在问题。问题出在尝试从 random 列表中移除元素后,仍然尝试访问被移除的元素。这会导致越界错误,因为 random 列表的大小在每次迭代中都会减小,但在尝试访问 random.get(r) 时,仍然使用了原始的随机索引 r。你需要在移除元素后,直接使用 r 作为索引来访问元素,而不是再次调用 random.get(r)。以下是修复后的代码:

int size = 10;
for (int i = 0; i < 10; i++) {
    int r = (int) (Math.random() * (size));
        
    int removedElement = random.remove(r);
    permutations.add(removedElement);
    size--;
        
}

这样做可以确保每次都使用正确的索引来访问已经移除的元素。

英文:

What is wrong with this code?
I am trying to pick a random element from an ArrayList and move it to another ArrayList to create a permutation. It keeps giving me out of bounds errors.

int size = 10;
for (int i = 0; i &lt; 10; i++) {
	int r = (int) (Math.random() * (size));
		
	random.remove(r);
	permutations.add(random.get(r));
	size--;
		
}

答案1

得分: 1

问题在于指令的顺序,首先你从位置 r 移除,然后你尝试从位置 r 获取。

permutations.add(random.get(r));
random.remove(r);

此外,如果你想从集合中移除元素,如 ArrayList,我建议使用迭代器(Iterators)。迭代器有 next() 方法用于获取数组中的下一个元素,还有 remove() 方法用于移除当前元素,你可以参考 https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

英文:

the problem is the order of the instructions first you are removing from position r and you try to get from position r.

    permutations.add(random.get(r));       
    random.remove(r);

Moreover, If you want to remove from collections as arrayList I do recommend to use Iterators. Iterator has methos as next() for getting the next element in the array and remove() for removing the actual element you can check https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

huangapple
  • 本文由 发表于 2020年7月30日 14:08:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63167138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定