mutate array in JAVA - java

public class example
{
public static void main(String[] args)
{
int[] MyArray = new int[10];
MyArray[1] = 5;
int[] NewArray = MyArray;
NewArray[1] = 10;
System.out.println(MyArray[1]);
}
}
Why does the system print out 10 instead of 5?
It seems like whatever changes we made to element in NewArray, MyArray will change along, why?
I copy this pattern to initiate like int, string variables but they don't behave like this above, why? thanks guy, I am new to CS programming.

It seems like whatever changes we made to element in NewArray, MyArray will change along, why?
You aren't changing NewArray. You're changing the array that the value of NewArray refers to. It's like this:
NewArray is a variable (an unconventionally named one, but hey)
The value of NewArray is a reference
The reference refers to an object
It's really, really important to differentiate between variables, references and objects. Don't feel worried that it didn't just come to you immediately - this is a stage a lot of people go through when they first encounter a language like Java.
The values of MyArray and NewArray both refer to the same array, so if you make changes to the array via one variable, you still see the change when you then look at the array via a different variable.
I copy this pattern to initiate like int, string variables but they don't behave like this above, why? thanks guy, I am new to CS programming.
For int, that's a value type - the value of an int variable is the number itself, not a reference to an object.
For String, I suspect you were changing the value of the variable to refer to a different String object - not changing the contents of the String object itself (which you can't - strings are immutable in Java). For example:
String x = "first";
String y = x;
x = "second"; // This doesn't change the value of `y`
I like to think of variables as pieces of paper. For value type variables, the value is just written on the piece of paper:
int i = 10;
is like having a piece of paper with the name i, and a value of 10 on it.
For classes and arrays (which are reference types) the value on the piece of paper isn't the object - it's a way of navigating to the object. A bit like having someone's home address written on a piece of paper.
Suppose you have two pieces of paper with the same address written on them. If you rub one of them out and write a different address, that doesn't change anything about what will happen if someone looks at the other piece of paper and goes to that house. That's like the String example above.
The array example, however, is more like this: I write my home address on two pieces of paper, and give them to Fred and Ginger. Fred reads the address, visits my home, and paints the front door red. (He's modifying the object - my house - without changing his piece of paper at all.) Now if Ginger reads the address on his piece of paper and visits my home, he'll see a red front door.

The reason this happens is because when you say int[] NewArray = MyArray; this is copying the reference of MyArray to NewArray.
This reason you are copying the reference is because you do not call the new operator to instantiate a new array.
So, when you say NewArray[x] it is pointing to the x position in memory of MyArray (and hence the value in memory of MyArray). No new memory is allocated when you do int[] NewArray = MyArray; since the new operator is not called.

It is beacuse when you do =, this makes the new obkect to point to the old one. So any changes made to the new one will reflect in the old one to, as they are the same technically.
You should array.clone to avoid this.

You are not copying it's value. You say:
Java create "MyArray".
Java creates a variable poiting at an object
Java create another array "NewArray" that is the same as MyArray
Java creates a variable poiting at the same object as MyArray
Java change the value of NewArray[1] to 10
Java changes the value on the object it is poiting at, not the variable itself.
Hope you get it.
As a side note, you should use [0] instead of [1]. Arrays start at 0, like everything in programming. So, the array with 10 items you created starts at 0 and ends at 9. Take note of that.

Related

How does java handle object references while dealing with ArrayLists? [duplicate]

This question already has answers here:
Modify list has an affect on another list in java
(2 answers)
Closed 1 year ago.
While writing a piece of code, I observed an unusual behaviour.
There is a class object obj1 which has an array list of another class object obj2 called as list1. See the code for reference:
PriorityQueue<Obj2> pq = new PriorityQueue<>(Comparator);
pq.addAll(new ArrayList<>(obj1.getList()));
Obj2 obj2 = pq.poll();
obj2.setField("any value");
System.out.println(obj2);
System.out.println(obj1.getList().get(0));
Both of the sout statement above prints the value.
Why is this happening? I changed the value of obj2 reference in pq and not in Obj1 itself
While adding elements to the pq, if we don't use new ArrayList<>() then it's understandable if the both the references are pointing to same object but I have created a new ArrayList to add in pq, still this happening.
How does java handle object references while dealing with ArrayLists?
It's all references. Everything. All the way down.
Except primitives. The primitive types are int, long, double, float, byte, short, boolean, and char. That's it. The list is hardcoded and you can't make new primitive types.
So, aside from those, it is all pointers. When you write:
MyFoo foo = new MyFoo();
That's just syntax sugar for 2 separate statements:
MyFoo foo;
foo = new MyFoo();
Imagine the heap is a gigantic whiteboard.
So what's happening here is:
MyFoo foo; This makes a little postit for yourself. This postit is named 'foo', it is yours, you can't hand it to anybody else ('local variable' - hence the name 'local'), and it has just enough room to write a coordinate for that gigantic whiteboard, that's all it can hold. It is blank, for now.
new MyFoo() this goes to the whiteboard, finds some blank space on it anywhere, and writes a box, and then in that box, room for all the fields of your MyFoo class. If any fields are non-primitive, it's just enough room to write coordinates. (Each and every object is its own little box on this whiteboard and could be anywhere on it).
The expression new MyFoo() resolves to the coordinates of where you made that box. You then assign this to foo, so, copy down the location of that box on your little postit.
If you then do:
someMethod(foo);
What that does is: Grabs a new postit, copies those coordinates over to the new postit, and then hands the postit off to someMethod. Specifically:
Even if someMethod changes foo directly (foo =), that is: "They scratch out what was on the postit you gave them and write something new on it", which obviously has no effect whatsoever on your postit.
Once that method is done, they burn the postits. You never get them back. Which is fine, you gave them a copy.
If they FOLLOW the coordinates on that postit and take out their pen and edit the whiteboard, and then later on your follow YOUR postit, you will observe what they changed! . and [] are the dereference operators: That's java-ese for: "Take those coordinates, go over to the whiteboard and find the box, and now we do something to the stuff in the box', whereas = is "edit the postit, scratching out what was there and writing something else in".
With all that context:
obj1.getList() gets you the coordinates to the list object. This list object is simply a big sack of coordinates - of postits. NOT a list of Obj1s! A list of Obj1 references - of coordinates.
new ArrayList<>(that) makes a new arraylist (new box on the whiteboard), that constructor will dutifully copy each and every COORDINATE over. It does not copy each object. It can't, java has no idea how to copy arbitrary objects, and Lists can hold anything, so it doesn't know how.
You then 'poll' the top coordinate from this newly created list. Which is the same coordinate as what obj1.getList() has.
You then go to the whiteboard, following this coordinate (obj2.setField - I see a dot, so, that's 'follow the coords and get out your whiteboard pen'), and modify what is there.
Hopefully that clears up how it works. Keep thinking of that whiteboard. When reasoning about this stuff.
Solutions
The simplest solution is to adopt immutables as much as is reasonable. An immutable object is, effectively, the notion of writing the object in permanent marker. A string is immutable. it has no set or add methods at all. For example, str.toLowerCase() does not lowercase the string that str is pointing at. That method makes a new string instead. It's the equivalent of going to the whiteboard which has "hEllo!" written on it someplace, and then instead of wiping out the E and writing an e in its place (that'd be mutating, and no method in string lets you do this), toLowerCase() just draws a new little box on the whiteboard somewhere and copies the characters over, lowercasing them on the fly. The toLowerCase() call then returns the location of this new box.
If you apply the same ideas to public class Obj1, this problem goes away. So, don't call .setField, call .withField (which makes a clone but with that one field changed) or some such.
If that's not an option, you'd have to deep-clone the list, yes. This is incredibly annoying, because how deep does deep-clone mean? ArrayList itself can't simply deep-clone, you'd have to write it yourself. Something like:
List<Obj1> clone = new ArrayList<>();
for (Obj1 o : original) clone.add(new Obj1(o));
And you'd have to write the Object1(Object1 original) {} constructor yourself, copying each field. And, of course, for each non-primitive field pointing at a mutable object, you'd have to clone that too.
The JavaDoc for ArrayList(Collection<? extends E> c) says:
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
It doesn't say "copy".
There's also no "deep copy" mechanism in Java. Even if you use Object.clone (which in general you shouldn't), you will only copy the references inside this object. The references itself will still point to the original contents.
For example:
class Obj {
String a;
int b;
OtherObj c;
}
In memory this will look like this:
[Reference To String a] [Value of int b] [Reference to OtherObj c]
(only primitive types will be stored directly inside an object, everything else is a Class and will be stored as a reference. Even the primitive wrappers like Integer are classes and will be stored as references, but those primitive wrappers are immutable, though you can't change their inner values)
Though if you create a copy of this object, you will get a new memory location for the copy, but that memory location then will contain the same data: [Reference To String a] [Value of int b] [Reference to OtherObj c].
The same happens with ArrayList. In memory it looks like this:
[Reference to Element 1] [Reference to Element 2] [Reference to Element 3] ...
And if you copy that list, you'll get a copy of that part in memory. But all the references will still point to the very same objects.
This all may change with the introduction of Project Valhalla and Value types. But that may still take months or years.

Not understanding Java bracket array correctly?

I was programming a plugin in Java and I wanted to set 4 different Location objects. Because in school(C++) they taught us to use [] and I like them (brackets), I decided to do that. Oh boy, I was wrong(or maybe it was just my mistake) I came up with this code:
Location[] pos = new Location[4]; //an array (I guess)
Location loc = e.getBlock().getLocation(); //to get the position of a block
and then I set it in a for loop to iterate trough them like this:
for(int i = 0; i < 4; i++){
pos[i] = loc;
}
But! When I wanted to change any of the pos[x] variables, all of them changed. Could this be related to pointers or something?
Anyways. I changed my code to do it like this
Location loc = e.getToBlock().getLocation();
Location loc1 = e.getToBlock().getLocation();
Location loc2 = e.getToBlock().getLocation();
Location loc3 = e.getToBlock().getLocation();
This code fortunately works, but how would I go with more variables, what if I wanted something like 200 of them? Or maybe a dinamic "array".
You might be wondering why I said "array" in quotes, but I really have no idea how to call pos[] other than an array, even tho I know that an Array exists and it's something completely different.
You have to create a new Location object at each iteration in the for loop.
Now you are using the same object in all the array slots. The 'loc' variable is a reference to the object in the heap, so changing it spreads the changes to all the array,
They all changed because you set them all to be the same object: the one you assigned to loc. If you had put the call to e.getToBlock().getLocation() inside the loop, your 4 array elements would have been different objects.
Right now your getLocation function is only being called once which creates a single object. Call it inside your for loop.
for (int i = 0; i < 4; i++) {
Location loc = e.getBlock().getLocation(); //to get the position of a block
pos[i] = loc;
}
When I wanted to change any of the pos[x] variables, all of them changed
It's because you assign each element of your pos to same object. You are from C++ background, so you should have a knowledge about pointers. What you are doing is assigining a "pointer" to same object in all positions of pos.
what if I wanted something like 200 of them?
I am not sure if I understand you right. You can use an ArrayList which allows you to add elements dynamically, so you don't have to know its size in advance. Look at the docs.
Did you intend to assign for all the array items the same object loc?
If yes, here we go. As others suggest, you should call the function e.getBlock().getLocation() once each time you go through your loop. This gives different objects with the same value.
Another workaround is to copy the object, rather than only assign the reference.
What I think about your problem is that you are mixing copying and assignment. When you assign loc to the array items in your loop
for(int i = 0; i < 4; i++){
pos[i] = loc;
}
you assign it by reference, as it an object and not a primitive data type.
This means that the array items, after you assigned loc, have a only a reference to a memory position, when you change its value via any reference, all other references will have the new value, expected behaviour.
If you intend to initiate all the items of your array to loc, you should deep/shallow copy it, i.e., not assign it by reference. See here for an explanation on difference between copy and assignment. Here is an answer for deep copy using serialization

Java pointer behavior

So I was experimenting with a permutation algorithm a few days back and discovered something.
int y=5;
chomp(y);
System.out.println(y); Output is still 5. Obviously.
void chomp(int x){
y=y-1;
}
The problem starts here.
char[] a = {'a','b','c'};
chomp(a);
System.out.println(a);
void chomp(char[] a){
char temp = a[1];
a[1]=a[2];
a[2]=temp;
}// It swapped it, But I didnt return anything. And I didnt do "a = chomp(a);"
BUT MY OUTPUT IS acb. WHY??? I tried it with int and nothing affected, From my experience in c and c++ im thinking because char array gives the address or something. But there is no pointers in java right? So how can it be???
in java, arrays are reference types, so only their references are copied. Reference types behave like pointers.
ints are value types, so their values are copied.
try a = {'x','y','z'}; in the chomp function. It won't change anything, because you're not changing the value that was at a, but a itself.
Java is pass by value - always. Primitives and references are the things that are passed.
Both your examples are correct, of course.
The array example is able to do the swap because you did not change the reference that points to the array. You were able to chance its state, as you are free to do with any mutable object.
It's imporant to know, because objects live on the heap. You don't pass an object to a method; you pass a reference to the object out on the heap. You can't modify the reference, but you can modify the state of the object it points to if it's mutable.

When does a 'void' method affect the parameter, and when does it affect the original object?

I am brand new to programming, as well as to this website, so forgive me if I screw anything up. I'm having a heck of a time figuring out how to properly post my code in here.
package tester;
import java.util.*;
public class Mainclass2 {
public static void main(String[] args) {
int y = 3;
int[] x = {1, 2, 3, 4};
editnumbersArray(x);
editnumbersNotArray(y);
System.out.println(x[2]); **//now this was changed from 3 to 9...**
System.out.println(y); //but this one went unchanged.
}
//this accepts 'x[]' into the 'a[]' parameter.
public static void editnumbersArray(int[] a){
a[2] = 9; **//<---why does this one CHANGE the actual x[2] instead of just a[2]?**
}
//this accepts 'y' into the 'a' parameter.
public static void editnumbersNotArray(int a){
a = 9; **//<--while this one only changes 'a' instead of 'y'?**
}
}
So my question is basically typed in there as comments. Why does the array that is passed into the method change the values of the original array (x[]) when the int that is passed into the other method doesnt change? I'm sure it's a simple answer, but when I did my research I couldn't figure out what to search. I don't know what this is called so everything I searched led me the wrong way. Thanks for any help!!
EDIT: Thanks for that analogy with the address! That is by far the best way you could have explained it to me. So basically when you pass an array into a parameter, its passing a reference, not the actual value? So when I make adjustments within my method, its changing whatever the array is referencing?
I noticed that this also happens with a list. So the list isnt actually passed by value? It seems as if the array/list itself is basically passed in for editing, no matter what I name it within my method (a[] in this case.)
EDIT http://javadude.com/articles/passbyvalue.htm this page really cleared it up. And sorry for posting a duplicate question. The problem was that I didn't know what I was trying to ask. I had never even heard these terms "pass-by-value/reference", so now I know
Changing the value of the parameter itself never affects the argument in Java, because all arguments are passed by value. However, look at this method:
public static void editnumbersArray(int[] a){
a[2] = 9;
}
That assignment doesn't change the value of the parameter. The value of a is still the same reference, to the same array - it just changes the contents of the array.
Imagine if I wrote my home address on a piece of paper for you. It wouldn't matter what you did to that piece of paper - that wouldn't change where I lived. However, if you visited the address and painted the front door green, without ever changing the piece of paper at all, I would see that change.
It's very important to differentiate between different concepts:
A variable is a named storage location; it holds a value, which is always either a primitive value (e.g. an int) or a reference. In my example above, the piece of paper was like the variable.
A reference is just a value which allows you to navigate to an object. It's not the object itself. It's like the address on the piece of paper.
An object contains other variables. There may be several variables which all have values which are references to the same object. It's like the house in my example: I can write my address on several pieces of paper, but there's only one house.
An array is an object which acts as a container for other variables. So the value of a is just a reference to the array.
Java uses pass by value (what you want to search for) for everything. Essentially that means it makes a copy of the parameter that it then passes to the method. That means that you cannot change what something points at by using the = operator.
That is why the (int a) version doesn't change a.
However, in the case of an Object or an array it doesn't make a copy of the Object or array, it makes a copy of the reference to the Object or the array. That means that you have two variables, the original on and the, in your example, (int[] a) one that both point to the same spot in memory. Changes to either variable will affect the other variable.
Pass by value, pass by reference, and pass reference by value are the types of things you want to search on for more information.

Passing by reference ruining everything :(

Hey people i have this structure for the search tree
class State
{
//CLASS STATE
int value;
char[][] state; //the game Grid
State child[]; // children of current state, maximum is 8
State(char[][] src)
{
state=src;
child=new State[8];
}
this is the root node definition
State rootNode = new State(currentGrid);
rootNode.value=-1;
int v =maxValue(rootNode,depth);
after the end of recursion in the max value function the array in rootNode should not be edited since its the the first state but when i Display it i get an array filled with stuff which means that the rootNode.state passed by reference to the max value function :(
//i am trying to implement MiniMax Algorithm.
If you don't want objects that are passed as parameters to be changed, pass in a copy (or make a copy of the parameter inside the method).
Note that char[][] means you have an array of char arrays, i.e. you are working with objects and if you copy the first level you still might have a reference to the second.
Thus you might have to loop through the first level/dimension and copy all the arrays in there, like this:
char target[][] = new char[state.length][0];
for( int i = 0; i < state.length; ++i ) {
target[i] = Arrays.copyOf(state[i], state[i].length);
}
If you need, you can easily create a copy of the array through Arrays.copyOf
You can also create a deep copy. How to do this has been answered here: How to deep copy an irregular 2D array
Yes, Java passes references to arrays and not the array as a value. So if you give a reference to your internal state away, the receiver can change it and the change is "visible" in the source (in fact: it's only one array that has been changed and all reference holders will see the change).
Quick fix/solution: clone your state array and pass a reference to this clone instead of the original. This will keep your internal root state unmodified.

Categories