I'm confused about ArrayList
with another variable that can change the value from another class.
I have two classes and two examples with the ArrayList
and Object
variables.
Can somebody help me to understand why it's different and if there is a solution to make it have the same effect?
This is the code with ArrayList:
import java.util.List;
public class Test {
private String name = "Fifi";
void fill(List<Test> a) {
a.add(this);
}
}
import java.util.ArrayList;
import java.util.List;
public class B {
private List<Test> a = new ArrayList<Test>();
//a variable is empty
public B() {
// TODO Auto-generated constructor stub
Test oa = new Test();
oa.fill(a);// After this method is called, a variable has change with name is "FiFi"
}
public static void main(String[] args) {
new B();
}
}
And then, I have the same form like that with the object variable, but the result is not the same.
public class Test {
private String name = "Fifi";
void fill(Test b) {
b = this;
}
}
public class B {
private Test a;
// so a variable is null
public B() {
// TODO Auto-generated constructor stub
Test oa = new Test();
oa.fill(a);// after fill method is called, a still null!
}
public static void main(String[] args) {
new B();
}
}
What is different from Arraylist and object variables like above? I do not understand the basics of how it's happening!