在Java中存储Enums的顺序

Sea*_*oyd 12 java algorithm enums guava

在java中,EnumSet使用long(RegularEnumSet)或long[](JumboEnumSet)将它包含的项存储在位掩码/位向量中.我现在遇到了一个用例,我有几千个域对象(让我们称之为Node),每个Flag对象都会按照每个对象不同的顺序显示枚举的所有项(让我们称之为).

目前我将Order存储为Guava ImmutableSet,因为这可以保证保留插入顺序.但是,我使用了本页中介绍的方法来比较a EnumSet<Flag>,an ImmutableSet<Flag>和a 中的内存使用情况Flag[].以下是a)Flag有64个枚举项和b)所有三个变量包含所有64个项的结果:

EnumSet:32字节
ImmutableSet:832字节
数组:272字节

所以我的问题是:是否有一种聪明的方法将枚举排序打包成数值以使内存占用量小于数组的内存占用量?如果它有所不同:在我的用例中,我会假设订购总是包含所有枚举项目.

澄清:我的枚举比这小得多,我现在没有任何记忆问题,这种情况也不会给我带来记忆问题.只是在这种微观层面上,这种低效率会让我感到困惑.

更新:

在得到各种答案和评论的建议之后,我想出了这个使用字节数组的数据结构.警告:它没有实现Set接口(不检查唯一值),并且它不会扩展到超出字节可容纳的大枚举.此外,复杂性非常糟糕,因为必须重复查询Enum.values()(请参阅此处讨论此问题),但这里是:

public class EnumOrdering<E extends Enum<E>> implements Iterable<E> {
    private final Class<E> type;
    private final byte[] order;

    public EnumOrdering(final Class<E> type, final Collection<E> order) {
        this.type = type;

        this.order = new byte[order.size()];

        int offset = 0;
        for (final E item : order) {
            this.order[offset++] = (byte) item.ordinal();
        }

    }

    @Override
    public Iterator<E> iterator() {
        return new AbstractIterator<E>() {
            private int offset = -1;
            private final E[] enumConstants = type.getEnumConstants();

            @Override
            protected E computeNext() {
                if (offset < order.length - 1) {
                    return enumConstants[order[++offset]];
                }
                return endOfData();
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

内存占用量为:

EnumOrdering:104

到目前为止,这是一个非常好的结果,感谢bestsss和JB Nizet!

更新:我已经将代码更改为仅实现Iterable,因为其他任何东西都需要对equals/hashCode/contains等进行合理的实现.

Ope*_*uce 6

是否有一种聪明的方法将枚举排序打包成数值

是的,您可以将排序表示为数值,但要使用它,您需要转换回byte/int数组.而且因为有64个!64个值的可能排序,64!大于Long.MAX_VALUE,你需要将数字存储在一个BigInteger.我想这将是存储顺序的最节省内存的方式,尽管你在内存中获得的是由于必须将数字转换为数组而导致的时间损失.

对于在数字/数组表示之间进行转换的算法,请参阅此问题.

这是上面的替代方案,不知道它是否与那个一样有效,并且你必须将代码转换intBigInteger基于 - 但它应该足以给你这个想法:

/**
   * Returns ith permutation of the n numbers [from, ..., to]
   * (Note that n == to - from + 1).
   * permutations are numbered from 0 to n!-1, if i is outside this
   * range it is treated as i%n! 
   * @param i
   * @param from
   * @param n
   * @return
   */
  public static int[] perm(long i, int from, int to)
  {
    // method specification numbers permutations from 0 to n!-1.
    // If you wanted them numbered from 1 to n!, uncomment this line.
    //  i -= 1;
    int n = to - from + 1;

    int[] initArr  = new int[n];             // numbers [from, ..., to]
    int[] finalArr = new int[n];             // permutation of numbers [from, ..., to]

    // populate initial array
    for (int k=0; k<n; k++)
      initArr[k] = k+from;

    // compute return array, element by element
    for (int k=0; k<n; k++) {
      int index = (int) ((i%factorial(n-k)) / factorial(n-k-1));

      // find the index_th element from the initial array, and
      // "remove" it by setting its value to -1
      int m = convertIndex(initArr, index);
      finalArr[k] = initArr[m];
      initArr[m] = -1;
    }

    return finalArr;
  }


  /** 
   * Helper method used by perm.
   * Find the index of the index_th element of arr, when values equal to -1 are skipped.
   * e.g. if arr = [20, 18, -1, 19], then convertIndex(arr, 2) returns 3.
   */
  private static int convertIndex(int[] arr, int index)
  {
    int m=-1;
    while (index>=0) {
      m++;
      if (arr[m] != -1)
        index--;
    }

    return m;
  }
Run Code Online (Sandbox Code Playgroud)

基本上,你的init数组以其自然顺序开始,然后遍历你的最终数组,每次计算下一个应该放置哪些剩余元素.此版本通过将值设置为-1来"删除"init数组中的元素.使用一个List或者更简单LinkedList,我只是从我躺在的旧代码中粘贴它.

使用上述方法并将其作为main:

public static void main(String[] args) {
    int n = (int) factorial(4);
    for ( int i = 0; i < n; i++ ) {
      System.out.format( "%d: %s\n", i, Arrays.toString( perm(i, 1, 4 ) ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

您将获得以下输出:

0: [1, 2, 3, 4]
1: [1, 2, 4, 3]
2: [1, 3, 2, 4]
3: [1, 3, 4, 2]
4: [1, 4, 2, 3]
5: [1, 4, 3, 2]
6: [2, 1, 3, 4]
7: [2, 1, 4, 3]
8: [2, 3, 1, 4]
9: [2, 3, 4, 1]
10: [2, 4, 1, 3]
11: [2, 4, 3, 1]
12: [3, 1, 2, 4]
13: [3, 1, 4, 2]
14: [3, 2, 1, 4]
15: [3, 2, 4, 1]
16: [3, 4, 1, 2]
17: [3, 4, 2, 1]
18: [4, 1, 2, 3]
19: [4, 1, 3, 2]
20: [4, 2, 1, 3]
21: [4, 2, 3, 1]
22: [4, 3, 1, 2]
23: [4, 3, 2, 1]
Run Code Online (Sandbox Code Playgroud)

这是ideone上的可执行版本.

判断BigInteger.bitLength(),应该可以存储不超过37个字节的64个元素的排序(加上使用BigInteger实例的开销).我不知道是否值得这么麻烦,但这是一个很好的运动!