Java枚举是否被视为原始类型或引用类型? [英] Are Java enums considered primitive or reference types?

查看:93
本文介绍了Java枚举是否被视为原始类型或引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个枚举对象,它被认为是一个原语还是一个引用?

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

推荐答案

它是一个引用类型。 Java原语是 boolean byte short char int long float double

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

您可以通过调用<获取枚举常量的值code> ordinal(),由EnumSet和EnumMap iterator 使用,并以自然顺序遍历元素(枚举常量的顺序)声明)

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);

这篇关于Java枚举是否被视为原始类型或引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆