This week's book giveaway is in the Design and Architecture forum. We're giving away four copies of Communication Patterns: A Guide for Developers and Architects and have Jacqui Read on-line! See this thread for details.
class CloneTest { public static void main(String[] args) { int ia[ ][ ] = { { 1 , 2}, null }; int ja[ ][ ] = (int[ ] [ ])ia.clone(); System.out.print((ia == ja) + " "); System.out.println(ia[0] == ja[0] && ia[1] == ja[1]); } } What is the difference between ia and ja Any help is greatly appreciated. -Jay
Arrays are Objects in java Here a shallow cloning is happening ia and ja becomes two different arrays of array references Thats why ia==ja becomes false and ia[1] == ja[1] becomes true Ragu [This message has been edited by Ragu Sivaraman (edited September 23, 2001).]
since this is a bidimensionnal array of int, null stands here for the reference to the second array so this is allowed as far as I know. But I think that the following declaration would not be accepted by the compiler int[][] array = {{1,2},{1,null}}; Val
Here a shallow cloning is happening ia and ja becomes two different arrays of array references Thats why ia==ja becomes false and ia[1] == ja[1] becomes true Ragu Thanks Ragu. Some follow up questions, 1. What is Shallow Cloning int ia[ ][ ] = { { 1 , 2}, null }; int ja[ ][ ] = (int[ ] [ ])ia.clone(); 2. How is ia[1] (which is null) = ja[1] (which is null) as two nulls cannot be equal 3. is ia[0][0]=ja[0][0] (is it 1) and ia[0][1]=ja[0][1] (is it 2)
hello jay, shallow cloning is when you simply call the clone() method on an object which produces an exact copy of that object. deep cloning happens when the object you call is an aggregate object which implements the Cloneable interface. this interface is a marker interface which tells you that when you call clone() on this aggregate object, it will recursively clone all the objects it contains references to. kind regards, james
Hi guys, The Object.clone() method does a 'shallow copy'. It will copy all the fields of the cloned object; but if any of them are reference fields (non-primitive type variables) then only a copy of the reference is made. It will not create and copy the objects referenced.. For example, if a class has a field <code>Object myObject</code> the clone will reference the same 'myObject'. Any changes made to the cloned 'myObject' will be seen in the original 'myObject'. If you want entirely new copies you must override the clone() method to create copies of the referenced objects. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform