English 中文(简体)
EnumSet pre - 1.5假枚举?
原标题:
  • 时间:2009-04-13 20:11:55
  •  标签:

最近我一直都做很多

enum Thing {

    /* etc etc */

    static final Set<Thing> allThings = EnumSet.allOf(Thing.class);

}

我希望类似的事情在前1.5 Java,即我希望类似:

final class Thing {

    private Thing(); // control instances within class

    static final Thing instance0 = new Thing();
    static final Thing instance1 = new Thing();

    static final Set allThings = // ?????
}

我该怎么办呢?

最佳回答

是什么:

final class Thing {

  static final Set allThings = new HashSet();

  private Thing() {
      allThings.add(this);
  } // control instances within class

  static final Thing instance0 = new Thing();
  static final Thing instance1 = new Thing();
}
问题回答

没有直接等效pre - 1.5 Java。

在Java 1.5之前,有两个(语法古怪)的选择如果你想立即初始化:

static final Set allThings = new HashSet(Arrays.asList(new Object[] {
    instance0, instance1, // etc.
}));

static final Set allThings = new HashSet() {{
    add(instance0);
    add(instance1);
    // etc.
}};

但是,这两种有其缺点。最简单的方法是简单地做一个静态方法

private static Set all() {
    Set ret = new HashSet();
    ret.add(instance0);
    ret.add(instance1);
    // etc.
}

You still have to remember to add any new members to the method, but it s easier to read (f或 most people).

有很明确的模式如何定义类型安全枚举pre-Jav 5环境。

它年代基本上一个类与<代码>公共最终静态> < /代码字段的值和一个私有构造函数(或更多)。

唯一的“硬”越来越像序列化细节(主要是通过实施<代码> readResolve() < /代码>)。

< a href = " http://www.javaworld.com/javaworld/javatips/jw-javatip122.html " rel = " nofollow noreferrer " >这Javaworld提示< / >对此事非常深入,< a href = " http://www.javaworld.com/javaworld/javatips/jw-javatip133.html " rel = " nofollow noreferrer " > < / >这个有更多的话要说。

在下列解决方案中,每个枚举类扩展了一个抽象基类AbstractEnum,和有自己的所有值自动生成并存储在一个静态地图的基类。

 public abstract class AbstractEnum
  {
    private final static Map/*<Class,Collection<AbstractEnum>>*/ allEnums 
      = new HashMap();

    protected AbstractEnum()
    {
      Collection/*<AbstractEnum>*/ allValues 
        = (Collection) allEnums.get(getClass());
      if (allValues == null)
      {
        allValues = new HashSet();
        allEnums.put(getClass(), allValues);
      }
      allValues.add(this);
    }

    protected static Collection/*<AbstractEnum>*/ getAllValues(Class clazz)
    {
      return Collections
        .unmodifiableCollection((Collection) allEnums.get(clazz));
    }
  }

  final class Thing extends AbstractEnum
  {
    final static Thing thing0 = new Thing();

    final static Thing thing1 = new Thing();

    private Thing()
    {}

    static Collection/*<Thing>*/ getAllValues()
    {
      return getAllValues(Thing.class);
    }
  }

注意,它仍然需要一些额外的重要的特性,比如线程安全性和序列化(saua文章中所描述的)。





相关问题
热门标签