gpt4 book ai didi

java - 为什么不能通过用不同大小的数组替换变量来重新分配数组的大小?

转载 作者:行者123 更新时间:2023-12-01 13:19:23 26 4
gpt4 key购买 nike

这是我在这里的第一篇文章,所以请友好! :)

假设我有这段代码:

public static void reassign (int[] nums) {
int[] A = {10,11,22};
A = nums;
}

public static void main(String[] args) {
int[] nums = {0,2};

reassign(nums);
System.out.println(nums[1]);
}

为什么我的答案是 2,而不是 11?它与数组的相对大小有关吗?

最佳答案

当你这样做时,

public static void reassign (int[] nums) {
int[] A = {10,11,22};
A = nums;
}

您将A作为nums的引用,并且您引用的nums是来自参数的一个,而不是来自主要方法。它的两个不同的变量

你应该这样做:

static int[] nums = {0,2}; //initial value of nums

public static void reassign (int[] arr) {
nums=arr;
}

public static void main(String[] args) {

int[] A = {10,11,22};
System.out.println("before reassign:"+nums[1]);
reassign(A);
System.out.println("after reassign:"+nums[1]);
}

输出:

    before reassign:2
after reassign:11

关于java - 为什么不能通过用不同大小的数组替换变量来重新分配数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22166799/

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