return copy instead of referance to collection

S

sakcee

is there a way to return a copy of collection instead of referance to
collection itself


I have a wrapper class to a collection('Big' HashMap) data structure.
I want to give an accessor method
but I want to return a copy of the structure instead of refernace to
structure

should I copy key by key?, can i use clone? is there a way to give
final referance so that user can not
chnage it?

which is better ?

thanks
 
D

Daniel Pitts

is there a way to return a copy of collection instead of referance to
collection itself

I have a wrapper class to a collection('Big' HashMap) data structure.
I want to give an accessor method
but I want to return a copy of the structure instead of refernace to
structure

should I copy key by key?, can i use clone? is there a way to give
final referance so that user can not
chnage it?

which is better ?

thanks

There are a few options.
Collections.unmodifiable* will give you a wrapper Map or Collection
which the client cannot modify. It will be a view of the existing
collection, so that if your code changes the Map, the unmodifiable map
will change, but any calls to set/put in the unmodifiable map will
through unsupported exception.

Alternatively, you can usually
public Map<T> getMap() {
return new HashMap<T>(oldMap);
}

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top