I’m currently doing something like this;
import java.util.*;
public class TestHashMap {
public static void main(String[] args) {
HashMap<Integer, String> httpStatus = new HashMap<Integer, String>();
httpStatus.put(404, "Not found");
httpStatus.put(500, "Internal Server Error");
System.out.println(httpStatus.get(404)); // I want this line to compile,
System.out.println(httpStatus.get(500)); // and this line to compile.
System.out.println(httpStatus.get(123)); // But this line to generate a compile-time error.
}
}
I want to ensure that everywhere in my code that there is a httpStatus.get(n), that n is valid at compile-time rather than finding out later at runtime. Can this be enforced somehow? (I’m using a plain text editor as my “development environment”.)
I’m very new to Java (this week) so please be gentle!
Thanks.
In this specific example, it seems like an enum is what you may be looking for:
An enum is a handy way of creating constants in Java, which are enforced by the compiler:
More information on how to use enums can be found in the Enum Types lesson from The Java Tutorials.