Start New Discussion within our Software Development Community

Im playing around with the clone method of arraylist and have a few questions. This is what i did with it:

ObjectMaker item1 = new ObjectMaker();
        ObjectMaker item2 = new ObjectMaker();
        ObjectMaker item3 = new ObjectMaker();

        ArrayList<ObjectMaker> arrayList = new ArrayList<ObjectMaker>();

        Object theList = arrayList.clone();

I was suprised that clone return an object. I dont see the point since you cant use your methods on it since its of the class Object.
Also I cant seem to do anything with theList object. I am trying to get/use arraylist but its not working:

ArrayList<ObjectMaker> arrayList2 = theList.arrayList;

The benefit of clone method is to make a local copy of the object you created and this method is inherited from Object class. The class inherit this method can also override it so that it can modify it for its own use. this is the reason it returns an object. Other benefit of returning object that you can cast this returned type to any supper class of the class you use it with;
for example you can cast the cloned ArrayList to list and reuse it as you like and so on.

In your example you are trying to access arrayList method from Object class which doesn't exist.Instead you should cast the value from Object to ArrayList like this:

ArrayList<ObjectMaker> arrayList2 = (ArrayList<ObjectMaker>)theList;

I hope my description is clear.

This question has already been answered. Start a new discussion instead.