Home | FAQ | Contact me

Java Maps

This is a collection of cool things to do with maps as they are encountered and I get excited enough to write them down. (I'm getting long enough in the Java tooth that I don't always recognize when I should note something for general interest.)

How to initialize a static Map in Java

Here's a neat trick that works real well. It's just complicated enough that it might not occur to you. This is Java 5+ stuff, of course.

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Ratings
{
	// ratings...
	public static final int	NR    = 0;	// not rated
	public static final int	G     = 1;	// general admission
	public static final int	PG    = 2;	// parental guidance suggested
	public static final int	PG_13 = 3;	// parent guidance strongly suggested/not under 13 years of age
	public static final int	R     = 5;	// restricted to mature audiences

	public static final Map< Integer, String >	RATINGS;

	static
	{
		Map< Integer, String >	map = new HashMap< Integer, String >();
		map.put( NR,    "NR" );
		map.put( G,     "G" );
		map.put( PG,    "PG" );
		map.put( PG_13, "PG_13" );
		map.put( R,     "R" );
		RATINGS = Collections.unmodifiableMap(  map );
	}
}

Afterward, it's easy to write code to convert from the integer (say, from a database column) to string and vice-versa. It's also possible to use the integer variables as "manifest constants."

Enumerations

Certainly, the last illustration lends itself also to the use of a Java enumeration. You instantiate the enumeration with its value, then refer to it include getting its String representation thereafter. You can even change the instance on the fly, though that spoils thinking of it as a manifest constant.

public enum Genre
{
	Action    ( "Action"          ),
	Adventure ( "Adventure"       ),
	Allegory  ( "Allegory"        ),
	Cartoon   ( "Cartoon"         ),
	Chick     ( "Chick flick"     ),
	Comedy    ( "Comedy"          ),
	Drama     ( "Drama"           ),
	Fantasy   ( "Fantasy"         ),
	History   ( "History"         ),
	Military  ( "Military"        ),
	Music     ( "Music"           ),
	Musical   ( "Musical"         ),
	Mystery   ( "Mystery "        ),
	Politics  ( "Politics"        ),
	Religious ( "Religious"       ),
	Science   ( "Science fiction" ),
	Suspense  ( "Suspense"        ),
	Thriller  ( "Thriller"        );

	private String	genre = null;

	private                Genre( String genre ) { this.genre = genre; }
	public final void   setGenre( String genre ) { this.genre = genre; }
	public final String getGenre()               { return this.genre; }
}