From: R.T.H.Chin <ro...@tb...> - 2003-09-20 18:45:56
|
Hi Peter, Last lecture I asked you about garbage collection and adding objects to a list. You said something like although you're adding a reference you can do as if you actually add the object itself. I think that is not entirely true: what if you add an object to the same list twice? If you then get one of the two additions and modify it then the other reference also refers to the modified object. Of course there will be no reason to add an object to a list twice, but if you do not understand that you are actually adding a reference (pointer) then adding an object twice may seem like copying it. Since many languages treat arguments by value by default, one could quickly get confused. B.t.w. Java treats primitive type - arguments (like int, double) by value and not by reference! Example: public class Test { public void aVoidMethod(int i, JustAClass aClass) { i = 5; aClass.setI(5); } public static void main(String[] args) { Test test = new Test(); int i1 = 10; JustAClass aClass1 = new JustAClass(); aClass1.setI(10); test.aVoidMethod(i1, aClass1); System.out.println(i1); System.out.println(aClass1.getI()); } } public class JustAClass { private int i; public int getI() { return i; } public void setI(int i) { this.i = i; } } Regards, Roy |