gpt4 book ai didi

java - 交换数组中的引用

转载 作者:行者123 更新时间:2023-12-01 18:37:23 25 4
gpt4 key购买 nike

好吧,我误解了这个问题。读了几遍后我发现了randInt实际上是我用来填充数组的方法本身。所以当它说打电话randInt时我认为这是某种递归调用。这应该是这样的:

  static int[] randInt(int i, int j) {
int[] temp = new int[(j - i) + 1];
for ( i = 0; i < j; i++) {
temp[i] = i + 1; // here i populate the array
}
System.out.println(Arrays.toString(temp)); // this prints [1, 2, 3, 4, 5]
for ( i = 1; i < j;i++){
swapReferences(temp[i], temp[randInt(0,i)] ); //this is some sort of recursive call that swaps the references
// btw that statement does not compile, how can i pass a method as a parameter?



}
return temp;
}

static void swapReferences(int a, int b) { //these parameters are wrong, need to be changed
//Method to swap references

}

很抱歉造成困惑,但我认为这应该是正确的。

最佳答案

Java 是按值传递的,因此您尝试重新分配参数是行不通的。

您需要做的是将数组本身和两个整数索引作为参数:

 int randInt = generate.nextInt(j-i) + 1; //this is gonna generate a # within the range of the array (so if array is size 5, generates something 1-5)
for ( i = 1; i < j;i++){
swapReferences(temp, i, randInt); //and this is my attempt at swapping the references
randInt = generate.nextInt(i) + 1 ;
}

static void swapReferences(int[] array, int a, int b){
int x = array[a];
array[a] = array[b];
array[b] = x;

}

可以改变参数,例如传递到方法中的数组,就像这里所做的那样,但您不能重新分配参数本身。

关于java - 交换数组中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com