静态对象没有存储在 HashMap 中。!

Static Objects are not getting stored in HashMap.!

我正在尝试创建一个映射,其中键作为字符串,值作为静态 class。但是当我打印数据时,它只存储最后一个键值对。谁能帮我解决这个问题。

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());
        }
    }
}

我得到的输出是:

IBM BOND
IBM BOND
IBM BOND

变化:

public static String assetName;
public static String assetType;

至:

public String assetName;
public String assetType;

static 字段是 class 级别,而不是 实例 级别 - 它们在所有实例之间共享。即使您正在调用不同对象的设置器,这些方法中也会更新完全相同的 2 个字段。