I running to a situation and I am very confused. Please help me out. Let's say I have a code like this.
MyClass obj1 = null; List<MyClass> testList = new ArrayList<MyClass>(); testList.add(obj1);//after this line of code, testList will have a "null" at first node obj1 = new MyClass();//after this line of code, testList still have a "null" //at first node... //What I want is that testList's first node will become a new //MyClass object Here is the steps in my understanding (probably incorrect...):
- obj1 stores the pointer that points to nothing...
- testList stores the pointer that points to the memory that holds the "new ArrayList()"
- testList add the pointer of obj1 in its collection.
- obj1 stores the pointer that points to a "new MyClass()"
- therefore, the obj1 in the testList should automatically points to the "new MyClass()"
Sorry I am new to programming... Any help is appreciated!
newcall before adding the object to the list. Look upjava pass by valueto answer all your questions.testList.add(obj1);// testList[0] and obj1 both reference the same object.obj1 = new MyClass();// Change obj1 to reference a new object. This will not cause all of the other references to the original object to be changed.