-1

I have a Class like this:
    public class MyClass
{

    private int id;
    private Map<String, String> myMap;

    public Map<String, String> getMyMap()
    {
        return myMap;
    }

    public void setMyMap(Map<String, String> myMap)
    {
        this.myMap = myMap;
    }

  
}

I added new setter method(overloading) because i didn't want to do set HashMap directly, and that's what you see now :

 public class MyClass
{

    private int id;
    private Map<String, String> myMap;

    public Map<String, String> getMyMap()
    {
        return myMap;
    }

    public void setMyMap(Map<String, String> myMap)
    {
        this.myMap = myMap;
    }

    public void setMyMap(String key , String value)
    {
        setMyMap(new HashMap<>(){{put(key, value);}});
    }
}

But because i used new HashMap<>(){{put(key, value);}} keyword every time i use this method , it create new Map and last items deleted .

So i have 2 question:

1-correct solution for set items by 2nd setter method

2-how i could use this setter method for multiple put's for this situations:

MyClass.setMyMap(new HashMap<>()
    {{
        put("title", title);
        put("id", id);
    }});

Thank you guys for your time .

  • 1
    [Every time someone uses double brace initialisation, a kitten gets killed.](https://stackoverflow.com/a/27521360/4949750) – Amongalen Mar 31 '21 at 10:58
  • Btw. your `setMyMap` is adding an element to the map, not setting it. Name the method accordingly, e.g. `addToMyMap`. – Amongalen Mar 31 '21 at 11:00
  • @Amongalen thank you for your warning about : https://stackoverflow.com/a/27521360/4949750 –  Mar 31 '21 at 17:14

2 Answers2

2

It depends on what your class does. But in general, I would not expose a setter for a map field.

It makes sense to add a constructor with a map argument, then do something like this:

public class MyClass
{
    private final int id;
    private final Map<String, String> myMap;

    public MyClass(int id, Map<String, String> myMap) {
        this.id = id;
        this.myMap = myMap;
    }

    public Map<String, String> getMyMap()
    {
        return myMap;
    }

    public void addPairs(Map<String, String> pairs)
    {
        myMap.putAll(pairs);
    }

    public void addPair(String key, String value)
    {
        myMap.put(key, value);
    }
}

Of course, you can expose an additional constructor:

    public MyClass(int id) {
    this.id = id;
    this.myMap = new HashMap<>();
}
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
0

Try some thing like this:

public void setMyMap(String key , String value) {
          if(myMap == null)
              myMap = new HashMap<String, String>();
          myMap.put(key, value);
}

You've already declared class field myMap and you want to use it in setMyMap method.
Do null check. If the field is null then create a new map. Then use put method to store data in the map.

the Hutt
  • 16,980
  • 2
  • 14
  • 44