This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About clone method usage?

 
Anto Telvin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic