I need a little help in java. I'm just a beginner of java. But I believed my foundation was pretty solid.
I was creating a simple java application when I encountered a slight problem with 2 of my ArrayList objects. Lets call them list1
and list2
. If I were to make list1 equal to list2 list1 = list2;
and add an element to list2 list2.add(obj)
, the element is added to list1 as well.
I did my research and found out I should do this instead list1 = new ArrayList(list2);
I didnt know java objects work like pointers. I thought only the values are being passed when 2 objects are equaled. I even created a simple test application which can set and get a number of an object. Again, I equaled both objects. Changing the element of 1 object seems to affect the other object as well. I dont know how I should search this on Google. Which is why I'm feeding you the whole story. I only get documents related to c programming. I feel like my foundation just got broken to pieces. I just down know how the =
works now. Tried doing
int num1 = 666;
int num2 = num1;
num1 = 42;
This doesnt affect num2. However,
Object obj1 = new Object();
Object obj2 = obj1;
obj1.changeSomeElement();
This affects obj2.
Now, I'm confused on how the =
works in java. Someone please share some useful docs for me to read please. Thanks!