与分配的数组在Java中其它阵列问题 [英] problem with assigning an array to other array in java

查看:101
本文介绍了与分配的数组在Java中其它阵列问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class TestingArray {

    public static void main(String[] args) {

        int iCheck = 10;
        int j = iCheck;
        j = 11;
        System.err.println("value of iCheck "+iCheck);

        int[] val1 = {1,2,9,4,5,6,7};
        int[] val2 = val1;
        val2[0] = 200;
        System.err.println("Array Value "+val1[0]);
    }

}

输出:

I确认10结果的价值
  数组值200

从上面的code我发现,如果任何数组将val2被分配到另一个阵列val1和如果我们改变val2的阵列中的任何值,其结果也反映了该数组VAL1而同样的情况是不与变量赋值。
为什么呢?

From the above code I found that if any array val2 is being assigned to another array val1 and if we change any value of val2 array, the result is as well reflected for the array val1 while the same scenario is not with variable assignment. Why ?

推荐答案

以下语句使 val2的引用同一个数组 VAL1

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

如果你想使一个副本,你可以使用 val1.clone()或<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28int%5B%5D,%20int%29\"><$c$c>Arrays.copyOf():

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

对象(包括集合类的实例,字符串整数等)以类似的方式工作,在这分配一个变量到另一个简单地拷贝基准,使得两个变量指的是相同的对象。如果有问题的对象是可变的,然后经由变量之一到它的内容作出后续的修改,也将通过其他可见。

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

基本类型( INT 双击等)的行为有所不同:有没有涉及引用和分配进行复印的值。

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

这篇关于与分配的数组在Java中其它阵列问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆