package com.mindprod.example;
import java.util.HashMap;
import java.util.Map;
import static java.lang.System.*;
/**
* example use of java.util.HashMap to modify keys and values.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2009-05-15 initial version
* @since 2009-05-15
*/
@SuppressWarnings( { "UnusedDeclaration" } )
public final class TestHashMapModify
{
/**
* Sample code to TEST HashMap Modifying
*
* @param args not used
*/
public static void main( String[] args )
{
final Map<String, Food> h = new HashMap<>( 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() );
}
}
static class Food
{
String colour;
String name;
float caloriesPerGram;
Food( final String name, final String colour, final float caloriesPerGram )
{
this.name = name;
this.colour = colour;
this.caloriesPerGram = 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;
}
}
}