我有一个充满自定义对象的 ArrayList。我需要将此 ArrayList 保存到 Bundle 中,然后稍后检索它。
由于 Serialized 和 Parcelable 都失败了,我现在只是尝试以某种方式保存与 ArrayList 中的索引关联的对象,然后在恢复 Bundle 并将对象添加回来时检查这些对象。
我拥有的是这样的:
保存 bundle 时:
//Create temporary array of the same length as my ArrayList
String [] tempStringArray = new String[myList.size()];
//Convert the enum to a string and save it in the temporary array
for (int i = 0; i<myList.size();i++){
tempStringArray [i] = myList.get(i).getType(); //returns the enum in string form
}
//Write this to the Bundle
bundle.putStringArray("List", tempStringArray);
现在我有了一个字符串数组,表示最初位于 ArrayList 中的对象的枚举类型。
所以,在恢复 Bundle 时,我正在尝试的是这样的:
//Temporary string array
String[] tempStringArray = savedState.getStringArray("List");
//Temporary enum array
ObjectType[] tempEnumArray = new ObjectType[tempStringArray.length];
for (int i = 0; i<tempStringArray.length;i++){
tempEnumArray[i]=ObjectType.valueOf(tempEnemies[i]);
}
所以,现在我有了最初位于 ArrayList 中的每个项目的枚举类型。
我现在想做的事情是这样的(将进入上面的 for 循环):
myList.add(tempEnumArray[i].ObjectTypeThisEnumRefersTo());
显然上面的“ObjectTypeThisEnumRefersTo()”方法不存在,但这最终是我想要找出的。这是可能的还是有其他方法可以做到这一点?
最佳答案
要从字符串中获取枚举类型 Enemy 的枚举值,请使用
Enemy.valueOf(String).
Enemy.valueOf("SPIDER") 将返回 Enemy.SPIDER,前提是您的枚举看起来像
enum Enemy { SPIDER, BEE};
编辑:事实证明,Zippy 也有一组固定的 Enemy 对象,每个对象都映射到 EnemyType 的每个值,并且需要一种从给定 EnemyType 中查找 Enemy 的方法。我的建议是创建一个
HashMap<EnemyType, Enemy>
并在创建时将所有对象放入其中,然后在反序列化时使用 HashMap 将字符串转换为枚举值,并将枚举值转换为 Enemy 对象。
后来我想到,根据 Enemy 中的逻辑量,您可能需要考虑废弃 Enemy 或 EnemyType 并将它们组合成一个参数化枚举,类似于这里的 Planet 示例:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 这将使您不必从字符串到最终对象执行两个步骤,并稍微简化一些事情,因为您毕竟不需要任何 HashMap 。
关于Java:获取与枚举关联的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041678/