简体   繁体   中英

How are values stored in array methods?

I'm not sure what the differences between the two code samples below are. (The first sample uses Picture.java from the standard library ):


//chooses a photo from your computer and reads RGB values from it
Picture mypic = new Picture(FileChooser.pickAFile());
Pixel pixelArray [] = mypic.getPixels();
pixelArray[0].setRed(255);
Pixel currentPixel = pixelArray[0];
currentPixel.setRed(0);
pixelArray[0].getRed()

output: 0 <== changes in variable currentPixel changes the value in pixelArray[0] without explicit declaration.


int array[] = new int[4];
array[0] = 1;
int firstElement = array[0];
firstElement = 9;
array[0]

output: 1 <== changes in variable firstElement does not change the value in array[0]


Why does the first code sample output 0 instead of 255, and why does the second code sample output 1 instead of 9?

currentPixel is a reference to pixelArray[0] , not a copy (ie. they point to the same object). On the other hand, firstElement is a copy of array[0] . In most cases when you assign an object to a variable, it will be a reference rather than a copy. If you want a new Pixel you will have to create one by calling the constructor.

The first one is passing the object around, an instance of Pixel. This is being done under the covers by using the address of the object in memory. Therefore anything you do to the object, is done to the object, and not a copy of the object. This is called 'by reference'.

In the second example int firstElement = array[0]; is taking the value at the memory location of array[0] and copying it to your new memory location firstElement. The two are not the same location in memory so when you update firstElement you are NOT updating array[0]. This is called 'by value'.

EDIT:

To answer your question: There is no such thing as an array method.

What you are getting is an 'Array offset'.

An array is a linear chunk of memory. It is split into equal sizes to handle the values that you ask it to (4 bytes for 32-bit Integer, 2 bytes for a 16-bit integer, 1 byte for a char, etc...). Addresses used to be 32-bit, now 64-bit. So when referencing objects array[0] is the base of the memory chunk array[1] is the base + sizeof(int), and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM