0

I was tweaking with the code a bit and found out that when I try to update the List<int[]> I'm able to do it like below but not able to do it when my list is of the type List<Integer>

List<int[]> res = List.of(new int[]{1, 2},new int[]{3,4});
        int[] tempList = res.get(0);
        tempList[0] = 100;
        System.out.println(Arrays.toString(res.get(0)));

        List<Integer> list = List.of(1,2,3,4);
        Integer x = list.get(2);
        x = 200;
        System.out.println(list);

Is the int[] passed by reference? or how does this work internally?

3
  • 1
    tempList[0] = 100; overwrites the array element. x = 200 only overwrites the local variable x which has no reference to the list where the previous value came from.
    – f1sh
    Commented May 10, 2023 at 17:47
  • Your two examples are not analogous. For something more comparable to the List<Integer> case, instead of tempList[0] = 100, try tempList = int[]{5, 6}. Commented May 10, 2023 at 18:11
  • Java is pass by value. Even arrays and class objects. The fact that you can access the contents of an array or object via a reference does not change this since you can't change the reference that was passed, only what it points to (or refers to).
    – WJS
    Commented May 10, 2023 at 21:11

2 Answers 2

3

For pass-by-value vs. pass-by-reference, see Is Java "pass-by-reference" or "pass-by-value"?.

In your case, the int[] case, you are not modifying the value of int[]. Instead, the value of int[] is a reference to an int array, and you are using that reference to modify the array, thus the original array is also modified.

List<int[]> res = List.of(new int[]{1, 2},new int[]{3,4});

When doing above, you initialized two int[] objects, let's call them array 1 and array 2 respectively, and you put the references of array 1 and array 2 inside a List<int[]> res.

int[] tempList = res.get(0);

When you do this, you get reference of array 1, and put it in variable tempList.

Therefore, there is always only 1 copy of array 1, so when you modify it through its reference you stored in tempList, that array 1 is modified, so when you try to retrieve it later using res.get(0), you retrieved the modified int[].

List<Integer> list = List.of(1,2,3,4);

This is similar. You created 4 Integer objects, and stored their references in List<Integer> list.

Integer x = list.get(2);

You get the reference of the third Integer object and put it in variable x.

x = 200;

This is what makes it different. You are directly changing variable x, from the reference of your previously created object to the reference of a newly created object of Integer that contains 200. However, this only changes variable x, but does not change the reference stored in your list.

That is why list ends up not changing when you check later.

0

All java objects are passed by reference. If you're familiar with C, that's usually called a pointer, although the term was considered somewhat tainted at the time java was designed (tainted in the sense one might think 'pointer' implies you can do things like 'I shall add 2 to it' or some such), so java calls them 'reference'. But, same thing.

And arrays are objects. Everything is, except the hardcoded list of primitives (int, long, double, float, boolean, short, byte, char).

So, given:

List<int[]> foo = new ArrayList<int[]>();
int[] x = {1, 2, 3};
foo.add(x);

This is happening:

  • Create a new arraylist. It has no name. Create it by writing some bytes on the heap.
  • Store the position in the heap (so not the list itself, the pointer to it) in variable foo. foo currently points at it. It may point at other lists in the future; other variables may point at this same arraylist later, too.
  • Create a new int array. It has no name. Create it by writing some bytes on the heap.
  • Store the position in the heap in variable x.
  • Call the list's add method. Pass a copy of the pointer (because in java, everything is pass-by-copy, but note that everything is a reference. Java never copies giant datastructures silently, just pointers). The add method does whatever it does.

Effectively, of course, it stores that pointer in its list structure.

A few more relevant insights:

Pass-by-copy

int x = 10;
String y = "Hello"; // strings are objects in java. y is a pointer.
test(x, y);
System.out.println(x);
System.out.println(y);

public void test(int x, String y) {
  x = 20;
  y = "World";
}

The above code prints 10, Hello - java is pass by copy. The fact that test changes its copy of this value is immaterial. The fact that the test changes its own variable (String y) that started out containing a copy of the pointer to the Hello object and changed it to point at some other object, is immaterial: They are copies; it doesn't affect the caller.

int[] x = [1, 2];
x[0] = 5;

x[0] is java-ese for: Take the x pointer. Dereference it (follow the pointer to the array object you find there). Find the first element and replace it with a new value. Hence, x[0] when x is null causes NullPointerException (NPE means: You tried to dereference null). Given that x[0] follows the pointer:

int[] x = {1, 2, 3};
test(x);
System.out.println(Arrays.toString(x));

public void test(int[] z) {
  z[0] = 8;
}

Would print 8,2,3. The method has its own copy of the pointer to the int array, but the test method follows this pointer and does something to the object it finds there. z is a copy but it points to the same thing. It's like if I have an address book with the address of a house on it. If I copy my page from my address book and hand you the copy, then:

  • If you tear you copy to pieces, I don't care. I won't even be able to tell you did this.
  • If you decide to follow the address on it and toss a brick through the window, oh, I care about that.

The first snippet was the equivalent of ripping up the copy of my address book page. This second snippet is the equivalent of walking to the address on it and tossing bricks.

Immutables

What you can do once you dereference a pointer depends on what kind of object is at the end of that pointer. For example, if it is an array, I can change a value of it, and you can't stop me from doing this (java does not have 'read only arrays' or some such). If it is, say, an AtomicInteger, I can call .set(10) on it and change the value it represents.

However, if the object's class has no accessible methods that change any of its state, then it's like a house that is bullet proof. It's impervious to brick throwing. You can hand copies of a pointer out all day without having to fear code you handed a copy of the address to throws a brick through the window. Cuz the windows are impervious to it. This is called 'an immutable object'.

String and Integer both are like this. This doesn't work:

Integer y  = new Integer(20);
y.setValue(40);

There is no set method. At all. Check the javadoc. Not a single method that changes anything. String - same thing. The toLowerCase() method does not 'change this strings contents'. It makes an entirely new string by lower casing this string; it does not change this string.

int[] is not immutable. Integer is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.