Java枚举自动递增条目? [英] Java enum auto-increment entries?

查看:118
本文介绍了Java枚举自动递增条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java是否允许像好的C或C C这样的意义上,您可以自动定义具有增长值的字段的枚举,并以可选的给定值开始?

Does Java allow something like good ol' C or even C# in the sense that you can define an enum with fields that grow in value automatically, and start at an optionally given value?

例如

在C或C#中:

enum Foo { A = 10, B, C, D = 5000, E, Fish };

收益A = 10,B = 11,C = 12,D = 5000,E = 5001, Fish = 5002。

Yields A = 10, B = 11, C = 12, D = 5000, E = 5001, Fish = 5002.

推荐答案

在Java中,您无法明确指定序数值。他们总是自动增加,从0开始,无法控制它。

In Java you can't specify the ordinal values explicitly at all. They always autoincrement, from 0, with no control over it.

如果你想要其他自定义值,你需要把它们放在构造函数调用中并自己存储。你可以获取自动增量,但是它是如此的:

If you want other custom values, you need to put them in constructor calls and store them yourself. You can get autoincrement, but it's icky as heck:

import java.util.EnumSet;

// Please don't ever use this code. It's here so you can point and laugh.
enum Foo 
{ 
    A(10), B, C, D(5000), E, Fish;

    private static int nextValue;
    private int value;

    private Foo()
    {
        this(Counter.nextValue);
    }

    private Foo(int value)
    {
        this.value = value;
        Counter.nextValue = value + 1;
    }

    public int getValue() 
    {
        return value;
    }

    private static class Counter
    {
        private static int nextValue = 0;
    }
}

public class Test
{
    public static void main(String[] args)
    {
        for (Foo foo : EnumSet.allOf(Foo.class))
        {
            System.out.println(foo.name() + " " + 
                               foo.ordinal() + " " + 
                               foo.getValue());
        }
    }
}

注意需要嵌套类,因为您无法访问枚举构造函数中的静态字段。 Ick,ick,舔。请不要这样做。

Note the need for the nested class, because you can't access static fields within an enum constructor. Ick, ick, ick. Please don't do this.

这篇关于Java枚举自动递增条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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