Alex Alex - 2 months ago 6
Android Question

How to fix error: "class, interface, or enum expected" when defining a Map outside of a class?

For my own

Logger
class I want to define a map to map the priority number back to a meaningful string like follows:

static Map<int, String> map = new HashMap<int, String>();
map.put(2, "VERBOSE");
map.put(3, "DEBUG");
map.put(4, "INFO");
map.put(5, "WARN");
map.put(6, "ERROR");


I wonder if there might be a function that does this automatically? But I do now know every function there is.

However, I define the lines just before my class definition, and then I get the error:

Error:(14, 8) error: class, interface, or enum expected


and not sure what it means (maybe I cannot declare variables outside a class?). I also tried to define the map inside the class, but then the
put
method cannot be resolved. I also notice, that I have not imported a
Map
module, and AndroidStudio does not seem to require a
Map
module (i.e. the name 'Map' is not red and underlined).

I am very confused (as usual); I just want to get a String "ERROR" if the priority-value is 6 and so on.

What am I doing wrong in my case...?

Answer

maybe I cannot declare variables outside a class?

Correct.

Use:

class Foo {
  static Map<Integer, String> PRIORITY_LABELS = new HashMap<>();

  static {
    PRIORITY_LABELS.put(2, "VERBOSE");
    PRIORITY_LABELS.put(3, "DEBUG");
    PRIORITY_LABELS.put(4, "INFO");
    PRIORITY_LABELS.put(5, "WARN");
    PRIORITY_LABELS.put(6, "ERROR");
  }

  // rest of class goes here
}

I also notice, that I have not imported a Map module, and AndroidStudio does not seem to require a Map module (i.e. the name 'Map' is not red and underlined).

That is because Android Studio does not know what to do with that code. Once you move them into the class, then Android Studio will realize that you are trying to use Map and HashMap and will ask you to import them.

Comments