Question

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.

Was it helpful?

Solution

In this specific example, it seems like an enum is what you may be looking for:

public enum HttpStatus {
  CODE_404("Not Found"),
  CODE_500("Internal Server Error");

  private final String description;

  HttpStatus(String description) {
    this.description = description;
  }

  public String getDescription() {
    return description;
  }
}

An enum is a handy way of creating constants in Java, which are enforced by the compiler:

// prints "Not Found"
System.out.println(HttpStatus.CODE_404.getDescription());

// prints "Internal Server Error"
System.out.println(HttpStatus.CODE_500.getDescription());

// compiler throws an error for the "123" being an invalid symbol.
System.out.println(HttpStatus.CODE_123.getDescription());

More information on how to use enums can be found in the Enum Types lesson from The Java Tutorials.

OTHER TIPS

Define constants like static final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500; and so on or use enum types instead of using "magic constants" in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top