Java是通过值传递还是通过引用传递或两者兼而有之?

Java是通过值传递还是通过引用传递或两者兼而有之?

问题描述:

考虑以下情况。

    List<Integer> listOne = new ArrayList<>();
    List<Integer> listTwo = new ArrayList<>();
    listOne.add(1);I think this happens due to 
    listOne.add(2);
    listOne.add(3);
    Collections.reverse(listOne);
    listTwo = listOne;  //listTwo has same reference 
    Collections.reverse(listOne);
    System.out.println(listOne);  //out put [1, 2, 3] 
    System.out.println(listTwo);  // same out put

Java是按值传递的,其中值(对于碰巧是非原始类型。我认为这为这种情况提供了java的生存。老实说为什么 java 试图避免通过引用传递并尝试与区别开来其他语言?而java仍然受到引用行为的影响?

Java is pass by value, where values (for non primitive types) happen to be references. I think this provide survival for java for this kind of scenario. To be honest why java try to avoid pass by reference and try to be different from some of other languages? while java still suffering from pass by reference behaviors?

编辑:另外请一些人解释上面代码中发生的事情

additionally please some one explain what happen in above code

Java没有受到引用行为的影响,它让他们:)

Java does not suffer from pass by reference behaviors, it enjois them :)

当你写的时候


列表listOne = new ArrayList<>();

List listOne = new ArrayList<>();

你有需要考虑的事项:

1)一个变量,它是一块内存,名为 listOne

1) a variable, which is a chunk of memory, and is named listOne

2)堆上的一个对象,是一个ArrayList的实例,它是一个更大的内存块,没有名称

2) an object on the heap, with is an instance of ArrayList, which is a larger chunk of memory, and has no name

3 )listOne变量的值,它不是内存块,而是放在变量listOne的内存中的一组0和1,并且该值也没有名称。

3) value of the listOne variable, which is not a memory chunk, but is a set of 0s and 1s placed in the memory of the variable listOne, and that value also has no name.

现在,当我们谈论listOne是通过值还是通过引用传递时,我们使用不精确的术语,这会导致误解。 listOne (事物1)根本没有传递,既不是值也不是引用。传递listOne(thing 3)的值,这样就可以访问ArrayList对象(第2项)。因此,如果使用名称listOne,但是意味着东西3,则通过值传递,如果意味着事情2,则通过参考传递。在这两种情况下,名称listOne不是东西2或东西3的正确名称,但是因为它简短而方便使用。

Now when we talk if listOne is passed by value or by reference, we use imprecise jargon which leads to misunderstanding. listOne (thing 1) is not passed at all, neither by value nor by reference. The value of listOne (thing 3) is passed, and this gives access to the ArrayList object (thing 2). So if we use name "listOne" but mean thing 3, it is passed by value, and if we mean thing 2, it is passed by reference. In both cases, name "listOne" is not correct name for thing 2 or thing 3, but it is used because it is short and convenient.