Have you ever needed to have HashMap as constant values in the interface, but couldn't do because you do not know how to do it. Here are the two ways I got.
First: Define class that returns unmodifiable map.
Second: Define it using anonymous classes and initializer as shown below.
With this syntax, an anonymous extends the HashMap and uses 'put' in the initialization block.
I hope this is useful.
Kovil Pillai P.
First: Define class that returns unmodifiable map.
class ConstMaps
{
static Mapmaps = new HashMap();
static
{
maps.put("mobile", getMobileMap());
maps.put("car", getCarMap());
}
private static Map getMobileMap()
{
Map
Second: Define it using anonymous classes and initializer as shown below.
With this syntax, an anonymous extends the HashMap and uses 'put' in the initialization block.
public interface Const_2
{
float LEASTPRICE = 1000;
float MAXPRICEZ = 100000;
Map MOBILEMAP = new HashMap()
{
{
put("NOKIA", "Nokia 6121 Classic");
put("SONY", "Sony Ericsson TM506");
put("MOTOROLA", "Motorola Aura");
put("IPHONE", "Apple iPhone 3G");
}
};
Map CARMAP = new HashMap()
{
{
put("FORD", "Ford Capri");
put("VOLKSWAGEN", "VW Scirocco");
put("TOYOTA", "Toyota SpaceCruiser");
put("BMW", "BMW 116i");
put("VAUXHALL", "Vauxhall Frontera");
}
};
}
I hope this is useful.
Kovil Pillai P.
Comments