【发布时间】:2014-04-25 02:09:50
【问题描述】:
我有两个 EnumSet。
我想将某些值从一个转移到另一个,但在两个对象中保留那些被认为“不可移动”的值。示例代码...
Public enum MaterialTypes {
STONE,
METAL,
WOOD,
STICKS,
STRAW;
// STONE & METAL are "immoveable"...
public static EnumSet<MaterialTypes> IMMOVEABLE_TYPES = EnumSet.of(STONE, METAL);
}
EnumSet<MaterialTypes> fromTypes = EnumSet.of(CellType.STONE, CellType.WOOD, CellType.STICKS);
EnumSet<MaterialTypes> toTypes = EnumSet.of(CellType.METAL, CellType.STRAW);
// How to preserve the IMMOVEABLE types, but transfer all the other types from one object to the other?
// E.g. Desired result...
// fromTypes = STONE (i.e. STONE preserved, WOOD & STICKS removed)
// toTypes = METAL, WOOD, STICKS (i.e. METAL preserved, STRAW removed, WOOD & STICKS added)
我尝试了各种方法,但都涉及许多步骤和临时 EnumSet 的创建。我想知道是否有一种真正有效的方法以及(当然)它是什么。
这让我头疼!
谢谢。
更新:
我尝试的一种方法(我认为可能效率低下)以达到预期的效果...
EnumSet<MaterialTypes> tmpSet = fromTypes.clone(); // Create temporary copy of fromTypes
tmpSet.removeAll(MaterialTypes.IMMOVEABLE_TYPES); // Leave only the MOVEABLE types in tmpSet
fromTypes.retainAll(MaterialTypes.IMMOVEABLE_TYPES); // Leave only the IMMOVEABLE type in fromTypes
toTypes.retainAll(MaterialTypes.IMMOVEABLE_TYPES); // Leave only the IMMOVEABLE types in toTypes
toTypes.addAll(tmpSet); // Add the MOVEABLE types (originally in fromTypes)
【问题讨论】:
-
现在你的例子说
toTypes = METAL, WOOD, STRAW (i.e. METAL preserved, STRAW removed, WOOD & STICKS added)这没有意义。你能纠正一下吗?您能否也请澄清一下您正在尝试做什么?如果可能,请向我们展示您编写的执行此操作但您认为效率不高的代码。 -
啊 - 已更正,谢谢。 (告诉过你这让我很头疼!)我稍后会添加我尝试过的代码(当我解开我造成的混乱时!;-)
-
感谢 Radiodef - 我添加了一些似乎可以达到预期结果的代码,但对我来说似乎过于夸张了,特别是因为我非常频繁地执行此方法。