How does Arrays.sort() change the variable passed to it?

Possible Duplicate:
Is Java pass-by-reference?

I am a little confused here. How does Arrays.sort(a) modify the value of a?

int[] a = {9,8,7,6,5,4,3,2,1};
Arrays.sort(a);
System.out.println(Arrays.toString(a));

I thought java was pass by value...


Yes, Java is pass-by-value. However, what is getting passed by value here is the reference to the array, not the array itself.


Objects in Java are passed by value of reference. So if you pass in an object, it gets a copy of the reference (if you assign that reference to something else, only the parameter is modified, the original object still exists and is referenced by the main program).

This link demonstrates a bit about passing by value of reference.

public void badSwap(Integer var1, Integer var2)
{
  Integer temp = var1;
  var1 = var2;
  var2 = temp;
}

Those are references to objects, but they will not be swapped since they are only the internal references in the function scope. However, if you do this:

var1.doubleValue();

It will use the reference to the original object.


Arrays.sort不修改变量,它修改变量指向的数组对象。

链接地址: http://www.djcxy.com/p/3520.html

上一篇: 为什么我的Java方法不能更改传递的变量?

下一篇: Arrays.sort()如何更改传递给它的变量?