| Author |
About clone method usage?
|
Anto Telvin
Ranch Hand
Joined: Aug 12, 2008
Posts: 113
|
|
Hi all When we need a copy of array and two references we can use the clone(). eg: int[] a={1,2,3,4,5} int[] ca=(int[])a.clone(); here why i need to type cast it ? if i am removing that type cast also it is working thanks
|
Anto Telvin Mathew<br />Many of the life failures are people who did not realize how close they were to success when they give up. EDISON
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Anto telvin Mathew: here why i need to type cast it ? if i am removing that type cast also it is working thanks
If it works without the type cast then you don't have to type cast it, but it doesn't matter if you do.
|
Joanne
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
In Java 1.4 and earlier, all clone() could return was Object. Therefore, you always needed to cast the result to whatever it really is returning. Java 5.0 introduced covariant return types. It basically means that if you override (or implement) a method that is defined to return X, you can now declare to return anything that IS-A X. clone() is one such example; although at just a very few places so far, it has been changed for arrays to return the array type. I'm still a bit annoyed at Sun for not changing it all over the place. It can't be to break existing code - generics and collections have the same risk. I just call it plain laziness. Why was it so hard to make java.util.Date for instance return Date for clone() instead of Object?
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: About clone method usage?
|
|
|