Java Types Listed: Functionality

Hey, I'm a big fan of using enumerated types in Java to help with code reading and restricting invalid values. However, I was told that much more could be done in Java with enumerations than just creating a named group of possible values.

Can someone point out the basic functionality that Java enumerations allow, as well as an example, or perhaps a place where I could get more information about this function?

Thanks a lot, Black Vegetable

EDIT: As suggested, this question should ask what differences exist between an enumeration and a class in Java. I did not know that they are so powerful? What is the difference?

+3
source share
3

- , JVM- .

, enum (MyEnum) (VALUE1 VALUE2). , enum JVM *, VALUE1 VALUE2 , ( ... (, "Foo" == new String("Foo") false).

, enum Enum<T extends Enum<T>>, fasion ( name() valueOf()).

* Classloaders - ... .

+3

Java enum - .

:

:

  • ( enum java.lang.Enum , Java )

:

  • , valueOf values
  • ( Java)
+4

, , .

, . . . , , .

public enum SimpleUnits
{
    BROTHERHOOD_ELITE_TROOPER,
    CAPITOL_FREE_MARINE,
    IMPERIAL_BLOOD_BERET;

    public static SimpleUnit getUnit(SimpleUnits unit)
    {
        SimpleUnit result = null;
//      new SimpleUnit(enumeName, hpMax, speed, CC, MW, PW, LD, ST, MV, AC, W, A, COST);
        switch(unit)
        {
            case BROTHERHOOD_ELITE_TROOPER:
                result = new SimpleUnit(BROTHERHOOD_ELITE_TROOPER.name(), 5, 0.15, 12, 12, 12, 12, 3,
                        5, 3, 2, 1, 100, "images/units/eliteTrooper.png");
                break;
            case CAPITOL_FREE_MARINE:
                result = new SimpleUnit(CAPITOL_FREE_MARINE.name(), 5, 0.15, 12, 12, 12, 12, 3,
                        5, 3, 2, 1, 100, "images/units/freeMarine.png");
                break;
            case IMPERIAL_BLOOD_BERET:
                result = new SimpleUnit(IMPERIAL_BLOOD_BERET.name(), 5, 0.15, 12, 12, 12, 12, 3,
                        5, 3, 2, 1, 100, "images/units/bloodBeret.png");
                break;
        }
        return result;
    }

    public SimpleUnit getUnit()
    {
        return SimpleUnits.getUnit(this);
    }

    public static SimpleUnit getUnit(String enumeName)
    {
        return SimpleUnits.valueOf(enumeName).getUnit();
    }
}

I hope you find this helpful.

+2
source

All Articles