Do pointers in java actually exist?
I thoug开发者_运维百科ht I'm pretty experienced in java, but it seems that's not really the case, I just noticed something yesterday, something I used before but never really realised what it did. I googled but didn't find the answer to my question.
If I declare an int array, and use Array's static sort function to sort my array, I just need to type
Arrays.sort( numbers );
Instead of
numbers = Array.sort( numbers );
This might look very easy in C and C++ because you can use pointers there. So what I'm wondering is, how is this done? Is it an advantage sun has, or am I completely senseless here?
Pointers exist in java - all non primitive variables are pointers in java, aka references.
THey do not support the same set of operations as pointers in C tho - they are essentially opaque to the user of the language.
The reason Arrays.sort(array)
works is because array
is a "pointer", which allows the sort()
function access to the memory location that the array
variable points to.
Now, why doesn't:
void swap (Integer a, Integer b) {
Integer tmp = a;
a = b;
b = tmp;
}
work if you did
Integer x = 1;
Integer y = 2;
swap(x,y);
Its because java passes by value (which is a concept distinct from pointers). The pointer to 1
is given to swap()
, not as the value of the variable x
(which is a memory address, or pointer). Thus, manipulating the arguments in swap()
does nothing to effect the variable x
.
First, this belongs on StackOverflow. Second, you want to read the article Java is Pass-by-Value, Dammit!
It sorts the array in-place.
The sort
method receives a reference to the number
array (which is an object), and changes the values inside the array! No new array-object is created, it is thus good enough to just pass it to the sort
function.
PS: all source code of Java is open, you can go and read the sources of the sort
function yourself. You'll see, there be no magic. If Java is installed properly on your system, there should be a src.zip
in the Java home folder.
I assume numbers
is an int-array, and all arrays in Java are objects. So sort
is passed a reference to numbers
, and it can sort them in place.
This question should be migrated to Stack Overflow. The fact that Java has a NullPointerException
class should give you a strong hint as to whether Java uses pointers behing the scenes.
精彩评论