静态对象不会存储在HashMap中。

时间:2018-09-20 01:51:18

标签: java oop hashmap static-classes

我正在尝试创建一个键为字符串,值为静态类的Map。但是,当我打印数据时,它仅存储最后一个键值对。有人可以帮我吗?

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

1 个答案:

答案 0 :(得分:4)

更改:

public static String assetName;
public static String assetType;

收件人:

public String assetName;
public String assetType;

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