0

我有一个充满自定义对象的 ArrayList。我需要将此 ArrayList 保存到一个 Bundle 中,然后稍后再检索它。

在 Serializable 和 Parcelable 都失败后,我现在只是尝试以某种方式保存与 ArrayList 中的索引关联的对象,然后在恢复 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()”方法不存在,但这最终是我想要找出的。这是可能的还是有其他方法可以做到这一点?

4

1 回答 1

1

To get an enum value of the enum type Enemy from a string, use

Enemy.valueOf(String).

Enemy.valueOf("SPIDER") would return Enemy.SPIDER, provided your enum looks like

enum Enemy { SPIDER,  BEE};

EDIT: It turns out Zippy also had a fixed set of Enemy objects, each mapped to each value of EnemyType, and needed a way to find an Enemy from a given EnemyType. My suggestion is to create a

HashMap<EnemyType, Enemy> 

and put all the objects in there upon creation, then at deserialization convert strings to enum values and enum values to Enemy objects using the hashmap.

It later occurred to me though that depending on how much logic you have in Enemy, you might want to consider scrapping either Enemy or EnemyType and combine them into one parameterized enum, similar to the example with Planet over here:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html That would spare you from having to go two steps from a string to your final object and simplify things a bit as you wouldn't need any hashmap after all.

于 2015-03-13T21:20:50.670 回答