我有两个枚举集。
我想将某些值从一个转移到另一个,但在两个对象中保留那些被认为“不可移动”的值。示例代码...
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)