1

I'm new at Java and I came across a problem I couldn't find a solution to, so maybe somebody can help me out. When I write this code:

ArrayList<String> Liste = new ArrayList<>();
String Name;

Liste.add("Harry");
Name = Liste.get(0);
Name = "Dieter";

System.out.print(Liste.get(0));
System.out.print(Name);

The output is, as expected:

Harry
Dieter

However, if I change the type to a custom object:

ArrayList<Names_Class> Liste = new ArrayList<>();
Names_Class Name;

Liste.add(new Names_Class());
Liste.get(0).First_Name = "Harry";
Name = Liste.get(0);
Name.First_Name = "Dieter";

System.out.print(Liste.get(0));
System.out.print(Name);

The output becomes:

Dieter
Dieter

So it seems Java only copies a references or something. Could somebody explain what happens here, and how I can get a complete copy of a single item out of an ArrayList?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tsukeyo
  • 13
  • 3
  • See also: [How do I copy an object in Java?](https://stackoverflow.com/q/869033/5923139) – Aplet123 Dec 18 '20 at 22:09
  • 1
    *"seems java only copies a reference"* That is correct. It's why they (`Liste` and `Name`) are known as *reference variables*. – Andreas Dec 18 '20 at 22:13
  • *FYI:* Java naming convention is for *variable* names to start with lowercase letter, so they should be `liste` and `name`. – Andreas Dec 18 '20 at 22:13

1 Answers1

1

enter image description here

String type is stored in Stack. Object type is stored in Heap.

Liste.add("Harry");

You added a string value "Harry" somewhere in stack.

Name = Liste.get(0);

Then you gave it a reference name "Name"

"Dieter";

You created a new value 'Dieter' somewhere in stack.

Name = "Dieter";

'Name' now references the location of stack where 'Dieter' is stored.

System.out.print(Liste.get(0));

Liste.get(0) references 'Harry'.

System.out.print(Name);

'Name' references 'Dieter'

Meanwhile,

Liste.add(new Names_Class());

new Names_Class() appoints some memery space in heap for Names_Class()

Liste.get(0).First_Name = "Harry";

First object of Liste - First_Name references 'Harry'

Name = Liste.get(0);

'Name' references what Liste.get(0) is referencing.

Name.First_Name = "Dieter";

'Name' - First_Name references 'Dieter' This is identical as Liste.get(0).First_Name = "Dieter".

System.out.print(Liste.get(0));
System.out.print(Name);

They both prints same value since Name references same location as Liste.get(0)

  • Thank you for the explanation. This together with the Link from Aplet123 helped me solve my problem :) – Tsukeyo Dec 19 '20 at 09:18