Best way to get an enumeration using a numeric identifier

I need to create an enumeration with approximately 300 values ​​and be able to get its value by id (int). I currently have this:

public enum Country {
    DE(1), US(2), UK(3);

    private int id;
    private static Map<Integer, Country> idToCountry = new HashMap<>();
    static {
        for (Country c : Country.values()) {
            idToCountry.put(c.id, c);
        }
    }

    Country(int id) {
        this.id = id;
    }

    public static Country getById(int id) {
        return idToCountry.get(id);
    }
}

This listing will be used a lot, so I wonder how much this is the best performance solution.

I read http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html again and again, but could not find the part that describes what time it is

static {

}
Block is called

and if it is guaranteed that it will be called only once. So is that?

+4
source share
4 answers

. , , , - .

, , , . , , - final.


( ):

Country[] countries = new Countries[maxId + 1];
for (Country country : Country.values()) {
  countries[country.id] = country;
}

:

System.out.println(countries[1]);  // DE.

id idToCountry.get(Integer).

, , (, , , null ).

+3

0, 1, :

  • . Enum.values() , . , , .
  • id, .

, :

enum Country {
    A, B, C, D, E;
    private static final Country[] values = Country.values();

    public static Country getById(int id) {
        return values[id];
    }
}

UPDATE: , ordinal(). , :

public int getId() {
    return ordinal();
}
+4

. , . Enum , ( enum). ID, Enum public final int orthinal(), . 0 DE, 1 forUS 2 UK.

:

public enum Country {
DE, US, UK;

private static Map<Integer, Country> idToCountry = new HashMap<>();

    Country() {
       idToCountry.put(this.ordinal(), this);
    }

    public static Country getById(int id) {
        return idToCountry.get(id);
    }
}
+1

. , .

enum Country {
  DE(1), US(2), UK(3);

  public int id;

  Country(int id) {
  this.id = id;
}

 public static Country getCountry(int id) {
    Country[] c = new Country[Country.values().length];
    c = Country.values();
    return c[id];
  }
}

.

0

Source: https://habr.com/ru/post/1665852/


All Articles