我正在尝试使用键作为字符串和值作为静态类创建一个 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
陪伴而非守候
相关分类