开发者

References in Java

i was reading about how you can only pass by value in java and that the only way to swap the contents of two objects is by putting then in an array...passing the reference to the array object by value and then using that reference to swap 0-1 array location.

But i have a further question on this: Suppose i create an array such as:

List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
array.add(a);

So my question is when i "add" an object to an array (in this case Integer object)...do I just store the reference to the object in the array or do I actually copy the content of the object in the array...

Hypothetically, let's say we have a "delete reference" statement in java,..so will this retain the value of the object in the array?

List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
arra开发者_StackOverflowy.add(a);
delete a;

So will the array still hold the correct value??


You are putting just the reference in the list when you list.add() it.

The java way to "delete" a reference is to have nothing using it, so:

list.remove(a);
a = null;

Now it's an orphan and the garbage collector will reclaim the memory (eventually).

Just doing a = null; has no effect on the reference held by the List nor the Integer object itself.

Note: A List is NOT an array. Arrays are very different animals than Lists (or any other collection).

Edited to answer more questions from asker

An ArrayList is not an array, it is a List, whose implementation uses an internal array (that you don't have access to).

An array is defined like this: Object[] array = new Object[5]; - It has a fixed-size - you can't change the size once it has been created. A List on the other hand can grow as required (internally, an ArrayList creates a new, larger array and copies its values into the new array and throws away the old array as required).

Any action like "copying" an object is done by reference - only the "pointer" is copied. In java, creating a true "deep copy" is called "cloning" an object, and the JDK has support for this concept - see Clonable.


Hypothetically, let's say we have a "delete reference" statement in java,..so will this retain the value of the object in the array?

Since we do not know what this hypothetical statement is doing, that is hard to tell.

What your ArrayList holds is a reference to an Integer object. Any other reference you have to that object points to the exact same instance.

With Integer, that does not make much of a difference, because Integer is immutable.

Try with a mutable object like StringBuilder to see the effect:

List<Object> array = new ArrayList<Object>();
StringBuilder a = new StringBuilder("xxxxxx");
array.add(a);

a.setLength(0);  // clear the contents

System.out.println(array.get(0));  // will not print "xxxxxx" anymore
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜