无法向Collection添加枚举数组

时间:2016-04-09 22:05:04

标签: java arrays collections enums

此代码无效;

    ArrayList<BlockFace> cardinalDirections = new ArrayList<>();
    cardinalDirections.addAll(new BlockFace[] {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST});

这也不是;

ArrayList<BlockFace> cardinalDirections = Arrays.asList(new BlockFace[] {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST});

只有在我一次手动添加每个元素或遍历数组时,它才有效;

    ArrayList<BlockFace> cardinalDirections = new ArrayList<>();
    for (BlockFace face : new BlockFace[] {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST})
        cardinalDirections.add(face);

为什么前两个例子不起作用?

1 个答案:

答案 0 :(得分:0)

您的方法不起作用,因为ArrayList.addAll使Collection不是数组。

将枚举转换为ArrayList

List<BlockFace> list = Arrays.asList(BlockFace.values());