2016-04-09 65 views
-3

此代碼不起作用;無法將枚舉數組添加到Collection

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

爲什麼前兩個例子不起作用?

+0

'列表 cardinalDirections = Arrays.asList(新BlockFace [] {BlockFace.NORTH,BlockFace.SOUTH,BlockFace.EAST,BlockFace.WEST});'代替' ArrayList ' – Tunaki

+0

'addAll'沒有接受數組的重載。 – Savior

+2

而'Arrays.asList'有一個返回類型'List'。 – Savior

回答

0

您的方法不起作用,因爲ArrayList.addAll需要Collection而不是數組。

轉換枚舉ArrayList的

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

爲什麼會有任何問題呢? –