Are Java enums considered primitive or reference types?

前端 未结 4 1763
臣服心动
臣服心动 2021-02-01 12:28

If I have an enum object, is it considered a primitive or a reference?

4条回答
  •  长情又很酷
    2021-02-01 12:51

    It's a reference type. Java primitives are boolean byte short char int long float double.

    You can get the enumeration constant's value by calling ordinal(), which is used by EnumSet and EnumMap iterator and "traverses the elements in their natural order (the order in which the enum constants are declared)"

    You can even add your own members to the enum class, like this:

    public enum Operation {
      PLUS   { double eval(double x, double y) { return x + y; } },
      MINUS  { double eval(double x, double y) { return x - y; } },
      TIMES  { double eval(double x, double y) { return x * y; } },
      DIVIDE { double eval(double x, double y) { return x / y; } };
    
      // Do arithmetic op represented by this constant
      abstract double eval(double x, double y);
    }
    //Elsewhere:
    Operation op = Operation.PLUS;
    double two = op.eval(1, 1);
    

提交回复
热议问题