我正在尝试使用键作为字符串和值作为静态类创建一个 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 BONDIBM BONDIBM BOND
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
改变:
public static String assetName;
public static String assetType;
到:
public String assetName;
public String assetType;
static字段是类级别,而不是实例级别 - 它们在所有实例之间共享。即使您正在调用不同对象的 setter,这些方法中也会更新完全相同的 2 个字段。
添加回答
举报
0/150
提交
取消