File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes getting a copy of an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "getting a copy of an object" Watch "getting a copy of an object" New topic
Author

getting a copy of an object

imran quazi
Greenhorn

Joined: Dec 01, 2006
Posts: 18
Hi,

I have this code:

Now I want a copy of a1 assigned to a2, but the original a1 will not be affected, so if I remove an element from a2, from a1 it won't remove.

I don't want to use clone. Is there any way to do that?

Kindly help.

Advance thanks, imran
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

The API is your friend:

a2.addAll(a1)
imran quazi
Greenhorn

Joined: Dec 01, 2006
Posts: 18
Thanks a lot David,
I was doing the same thing, i.e, iterating the 1st array and putting the value in the 2nd one. this method does it more neatly.

BTW, this is ok for arrays, but what if its not an array? then is it possible to do what i asked for?
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

addAll is defined by the Collection interface, so it is supported by any concrete Class that implements this interface.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Well, to be fair, the Collection interface lists the method as optional. It can throw an UnsupportedOperationException in some cases. So in truth, there is no general answer to Imran's last question; it depends on the specific Collection implementation that we are talking about. Most collections implement this method, but a few, like the implementations returned by Collections.unmodifiableXXX() and Arrays.asList(), do not. The idea of optional methods in an interface is a bit odd, and in Java I think it's unique to the collections framework. Generally an interface promises that a method will be available in an implementing class. But with an optional method, the promise is that the method will be present in the class, but it may throw an exception. So the method is available, except that it really isn't.


"I'm not back." - Bill Harding, Twister
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: getting a copy of an object
 
Similar Threads
Compare two ArrayList
Comparing Two ArrayLists
want to know how to pick details from collections
Comparing Objects containing List
Read file from directory, update contents of the each file