This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About clone method usage?" Watch "About clone method usage?" New topic
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: 3419
    
  12
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: 19651
    
  18

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
wood burning stoves
 
subject: About clone method usage?
 
Similar Threads
Question regarding Cloneable interface and Subclasses
typecasting problem
immutable wrapper map
Object cast in Prototype pattern
Problem with declared type vs actual type