Search code examples
javaoophashmapstatic-classes

Static Objects are not getting stored in HashMap.!


I am trying to create a Map with key as a String and Value as a static class. But when I am printing the data, it only stores the last key-value pair. Can someone help me with this.

import java.util.HashMap;
import java.util.Map;

public class MapImplementation {

    public static class Asset {

        public static String assetName;
        public static String assetType;

        private void setAssetName(String name) {
            Asset.assetName = name;
        }

        private void setAssetType(String type) {
            Asset.assetType = type;
        }

        private String getAssetName() {
            return assetName;
        }

        private String getAssetType() {
            return assetType;
        }
    }


    public static void main(String[] args) {

        Map<String, Asset> map = new HashMap<>();
        Asset asset1 = new Asset();
        asset1.setAssetName("Vodafone");
        asset1.setAssetType("STOCK");
        map.put("Vodafone", asset1);

        Asset asset2 = new Asset();
        asset2.setAssetName("Google");
        asset2.setAssetType("STOCK");
        map.put("Google", asset2);

        Asset asset3 = new Asset();
        asset3.setAssetName("IBM");
        asset3.setAssetType("BOND");
        map.put("IBM", asset3);

        for (String str : map.keySet()) {
            Asset ast = map.get(str);
            System.out.println(ast.getAssetName()+" "+ast.getAssetType());
        }
    }
}

The output I am getting is:

IBM BOND
IBM BOND
IBM BOND

Solution

  • Change:

    public static String assetName;
    public static String assetType;
    

    to:

    public String assetName;
    public String assetType;
    

    static fields are class level, not instance level - they are shared across all instances. Even though you are calling setters of different objects, the exact same 2 fields are being updated in those methods.