![](/img/trans.png)
[英]How to get access to a HashMap of objects from the Objects in that HashMap. (Java)
[英]Static Objects are not getting stored in HashMap.!
我正在嘗試使用鍵作為字符串和值作為靜態類創建一個 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
改變:
public static String assetName;
public static String assetType;
到:
public String assetName;
public String assetType;
static
字段是類級別,而不是實例級別 - 它們在所有實例之間共享。 即使您正在調用不同對象的 setter,這些方法中也會更新完全相同的 2 個字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.