您可能想要對HashMap中的鍵或值執行四種常見類型的修改。
- 要更改HashMap鍵,請用get查找value對象,然後刪除舊鍵並將其與新鍵一起使用。
- 要更改值對象中的字段,請使用get鍵向上查看value對象,然後使用其setter方法。
- 要完全替換其中的值對象,只需在舊鍵處添加一個新的值對象即可。
- 要用基於舊值的對象替換值對象,請使用get查看值對象,創建新對象,從舊數據複製數據,然後將新對象置於同一個鍵下。
就像這個例子。
static class Food
{
// ------------------------------ FIELDS ------------------------------
String colour;
String name;
float caloriesPerGram;
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
public float getCaloriesPerGram()
{
return caloriesPerGram;
}
public void setCaloriesPerGram(final float caloriesPerGram)
{
this.caloriesPerGram = caloriesPerGram;
}
public String getColour()
{
return colour;
}
public void setColour(final String colour)
{
this.colour = colour;
}
public String getName()
{
return name;
}
public void setName(final String name)
{
this.name = name;
}
public String toString()
{
return name + " : " + colour + " : " + caloriesPerGram;
}
// --------------------------- CONSTRUCTORS ---------------------------
Food(final String name, final String colour, final float caloriesPerGram)
{
this.name = name;
this.colour = colour;
this.caloriesPerGram = caloriesPerGram;
}
}
// --------------------------- main() method ---------------------------
/**
* Sample code to TEST HashMap Modifying
*
* @param args not used
*/
public static void main(String[] args)
{
// create a new HashMap
HashMap<String, Food> h = new HashMap<String, Food>(149
/* capacity */,
0.75f
/* loadfactor */);
// add some Food objecs to the HashMap
// see http://www.calorie-charts.net for calories/gram
h.put("sugar", new Food("sugar", "white", 4.5f));
h.put("alchol", new Food("alcohol", "clear", 7.0f));
h.put("cheddar", new Food("cheddar", "orange", 4.03f));
h.put("peas", new Food("peas", "green", .81f));
h.put("salmon", new Food("salmon", "pink", 2.16f));
// (1) modify the alcohol key to fix the spelling error in the key.
Food alc = h.get("alchol");
h.put("alcohol", alc);
h.remove("alchol");
// (2) modify the value object for sugar key.
Food sug = h.get("sugar");
sug.setColour("brown");
// do not need to put.
// (3) replace the value object for the cheddar key
// don't need to get the old value first.
h.put("cheddar", new Food("cheddar", "white", 4.02f));
// (4) replace the value object for the peas key with object based on previous
Food peas = h.get("peas");
h.put("peas", new Food(peas.getName(), peas.getColour(), peas.getCaloriesPerGram() * 1.05f));
// enumerate all the keys in the HashMap in random order
for (String key : h.keySet())
{
out.println(key + " = " + h.get(key).toString());
}
}// end main
}
我希望這有助於
您可以*永遠不會*更改地圖中的鍵值。 – EJP 2010-11-21 00:33:07
因此從性能角度來看,我在這裏的解決方案是否正常?因爲每小時會有數千次這樣的電話 – lisak 2010-11-21 00:36:20
@EJP我在這裏改變的只是地圖的鑰匙 – lisak 2010-11-21 00:37:18