File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes About clone method usage? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About clone method usage?" Watch "About clone method usage?" New topic

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


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

Joined: Aug 05, 2005
Posts: 3742
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


If it works without the type cast then you don't have to type cast it, but it doesn't matter if you do.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

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?

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: About clone method usage?
It's not a secret anymore!