Good Day.
I am pretty sure that this question has been asked before but I couldn't find it.
Basically, how does the below code work:
import java.util.ArrayList;
public class Main{
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(10);
change(a);
System.out.println(a.get(0));
}
static void change(ArrayList v){
if(v.size() > 0){
v.set(0, "Hello");
}
}
}
It compiles and also runs successfully, printing "Hello". How could Java replace Integer with String?
I also tried adding in Main:
a.set(0, 1002);
for(Integer c: a){
System.out.print(c + " ");
}
System.out.println("");
Once again, very surprising. I thought that maybe somwhow a
gets changed to ArrayList<String>
but the set
method works normally?
Can anyone please explain this to me? Is this undefined behaviour?
Thanks.