Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getting a copy of an object

 
imran quazi
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API is your friend:

a2.addAll(a1)
 
imran quazi
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
addAll is defined by the Collection interface, so it is supported by any concrete Class that implements this interface.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic