我在重新分配数组中的值时遇到问题。
public static void main(String[] {
int[] arrayOfIntegers = new int[4];
arrayOfIntegers[0] = 11;
arrayOfIntegers[1] = 12;
arrayOfIntegers[2] = 13;
arrayOfIntegers[3] = 14;
arrayOfIntegers = {11,12,15,17};
}
为什么我无法按照我尝试过的方式重新分配值?如果我做不到,为什么我做不到?
最佳答案
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
因为 Java 不像其他一些语言那样具有解构赋值。
您的选择是:
如 Rohit 和 Kayaman 所示,将新 数组分配给数组变量,但这不是您所要求的。你说你想分配给元素。如果您将新数组分配给
ArrayOfIntegers
,则在不同变量或成员中引用旧数组的任何其他内容仍将引用旧数组。使用
System.arraycopy
,但它涉及创建一个临时数组:System.arraycopy(new int[]{11,12,15,17}, 0, ArrayOfIntegers, 0, ArrayOfIntegers.length);
System.arraycopy
会将元素复制到现有数组中。
关于java - 在数组中重新分配值的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18288888/