HashMap 中有四种常见的修改方式,你可能想要对键或值进行修改。
- 要更改 HashMap 键,可以使用 get 查找值对象,然后使用新键删除旧键并将其插入。
- 要更改值对象中的字段,请使用 get 按键查找该值对象,然后使用其 setter 方法。
- 要完全替换值对象,只需在旧键处放置一个新值对象即可。
- 要用基于旧对象的新对象替换值对象,请使用 get 查找值对象,创建一个新对象,从旧对象中复制数据,然后在相同键下放置新对象。
类似以下示例。
static class Food
{
String colour;
String name;
float caloriesPerGram;
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;
}
Food( final String name, final String colour, final float caloriesPerGram )
{
this.name = name;
this.colour = colour;
this.caloriesPerGram = caloriesPerGram;
}
}
public static void main( String[] args )
{
HashMap<String, Food> h = new HashMap<String, Food>( 149
,
0.75f
);
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 ) );
Food alc = h.get( "alchol" );
h.put( "alcohol", alc );
h.remove( "alchol" );
Food sug = h.get( "sugar" );
sug.setColour( "brown" );
h.put( "cheddar", new Food( "cheddar", "white", 4.02f ) );
Food peas = h.get( "peas" );
h.put( "peas", new Food( peas.getName(), peas.getColour(), peas.getCaloriesPerGram() * 1.05f ) );
for ( String key : h.keySet() )
{
out.println( key + " = " + h.get( key ).toString() );
}
}
}
我希望您能从中受益。