[Java] Can you explain this phenomenon?

Try your Java power.

See the code below. I'm trying to assign "D" to every value in an arrayList.

ExtentionForSample.java


ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
for(String str : arrayList) {
	str = "D";
	System.out.println(str);
}
System.out.println(arrayList);

result

D
D
D
[A, B, C]

Can you explain why this was the result?

answer

I just changed the reference destination of the local variable. .. ..

Let's explain

ローカル変数代入.png

I was just assigning a new reference to a local variable. Does not affect the referenced "A"

To fix

ExtentionForSample.java


//Omission
for(int i=0; i < arrayList.size(); i++) {
	arrayList.set(i, "D");
}
System.out.println(arrayList);

Use ArrayList.set (int index, E element)

result

[D, D, D]

By the way

ExtentionForSample.java


Map mapA = new HashMap<String,String>(){{put("1", "A");}};
Map mapB = new HashMap<String,String>(){{put("1", "B");}};
Map mapC = new HashMap<String,String>(){{put("1", "C");}};
arrayListMap.add(mapA);
arrayListMap.add(mapB);
arrayListMap.add(mapC);
for(Map map:arrayListMap) {
	map.put("2", "D");
}
System.out.println(arrayListMap);

result

[{1=A, 2=D}, {1=B, 2=D}, {1=C, 2=D}]

ローカル変数代入_map.png

Summary

When data is manipulated for the reference destination assigned to the local variable, it is reflected in the reference destination.

Recommended Posts

[Java] Can you explain this phenomenon?
Can you do it? Java EE
[Good news] You can still go with Java 8 !!
[JavaScript] Java programmers! You can understand JavaScript closures very easily!
Explain Java 8 lambda expressions
This is all you need WebSocket: Server = Java, Client = Java, JavaScript
[# 3 Java] Read this if you want to study Java! ~ Carefully selected ~
[Ruby comprehension check] Can you explain what is happening? && and and
Java history in this world
Java thread safe for you