• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

About clone method usage?

 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
reply
    Bookmark Topic Watch Topic
  • New Topic