The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time. The clone method is implemented by the class Object as a convenient, general utility for subclasses that implement the interface Cloneable, possibly also overriding the clone method, in which case the overriding definition can refer to this utility definition by the call:
"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
"If the facts don't fit the theory, get new facts" --Albert Einstein
Rusty Shackleford wrote:Object.clone() is not implemented in List.
...
Since you have List reference, you can't directly call it from ArrayList. One of the problems of using a base class reference. If you know your program will need an ArrayList and not another class that implements List, just use an ArrayList reference. clone() also returns an Object, so casting will be necessary.
Also, clone() returns a shallow copy. Are you sure that is what you want?
Steve
Rusty Shackleford wrote:Object.clone() is not implemented in List. From the Object.clone() docs:
The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time. The clone method is implemented by the class Object as a convenient, general utility for subclasses that implement the interface Cloneable, possibly also overriding the clone method, in which case the overriding definition can refer to this utility definition by the call:
Since you have List reference, you can't directly call it from ArrayList. One of the problems of using a base class reference. If you know your program will need an ArrayList and not another class that implements List, just use an ArrayList reference. clone() also returns an Object, so casting will be necessary.
Also, clone() returns a shallow copy. Are you sure that is what you want?
"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
"If the facts don't fit the theory, get new facts" --Albert Einstein
Hunter McMillen wrote:Casting to an arraylist wont fix the problem, you get a compile time error because, at compile time the jvm only sees the declaration of the type, it trusts the programmer to instantiate correctly. And there is no clone() method in the List api.
Note: I like Steve's solution to this problem better than mine because he uses methods from the Arraylist class instead of the generic List class
Hunter
"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Don't get me started about those stupid light bulbs. |