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?

3
  • See also: How do I copy an object in Java? Commented Dec 18, 2020 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. Commented Dec 18, 2020 at 22:13
  • FYI: Java naming convention is for variable names to start with lowercase letter, so they should be liste and name. Commented Dec 18, 2020 at 22:13

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation. This together with the Link from Aplet123 helped me solve my problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.