سؤال

In my case I have this to manipulate a shallow copy of given HashMap

public class SomeClass
{
    private HashMap<String, String> hashMap;
    public SomeClass( private HashMap<String, String> hashMap )
    {
        this.hashMap = (HashMap<String, String>) hashMap.clone();
    }
}

However eclipse suggests me to extract to local variable or method or add a cast and when I do so it keeps suggesting me same solutions :)

I've came to this post and from the accepted answer I dont find it very clear

"you're wasting memory with the new HashMap creation call"

And when I apply that to my code I'll have

if(songData.clone() instanceof HashMap)
{
    this.songData = (HashMap<String, String>) songData.clone();
}

I find that cosume more process as calling clone() twice.

Is there a better way to do this? Could my snippet be harmful to resouces?

هل كانت مفيدة؟

المحلول

Don't use clone. clone() is a badly designed method that requires too much knowledge of the object being cloned and is often implemented wrong by users anyway. (See Effective Java for more info about this)

The best way to copy the Map is to create a new map with the same data:

public SomeClass( HashMap<String, String> hashMap )
{
    this.hashMap = new HashMap<String,String>(hashMap);
}

Also as an FYI, public SomeClass( private HashMap<String, String> hashMap ) doesn't compile. You can't have parameters with a private keyword. Removing "private" from the parameter works.

you're wasting memory with the new HashMap call

This was in the answer to the other post you referenced because their code was:

private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)...

Where someMap was created with a call to new Hashmap() but then that reference was immediately replaced with a different HashMap.

It is irrelevant to your problem so you can ignore it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top