[英]java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Object[]
In my android project, I want to create a generic class to store all types of entities in sharedPreferences but give the error :在我的 android 项目中,我想创建一个通用类来在 sharedPreferences 中存储所有类型的实体,但给出错误:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Object[]
here is my code :这是我的代码:
public ArrayList<E> getItems(Context context) {
android.content.SharedPreferences settings;
List<E> objects ;
settings = context.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
if (settings.contains(ITEM_NAME)) {
String json = settings.getString(ITEM_NAME, null);
GsonBuilder gson = new GsonBuilder();
Type collectionType = new TypeToken<List<E>>(){}.getType();
E[] items = gson.create().fromJson(json,
collectionType); // in this line occurs error
objects = new ArrayList<E>(Arrays.asList(items));
} else
return null;
return (ArrayList<E>) objects;
}
Try:尝试:
List<E> items = gson.create().fromJson(json, collectionType);
That exception is complaining that you had an ArrayList object (which was returned from fromJson()
), but you attempted to cast it to an array with that assignment to E[] items
.该异常抱怨您有一个 ArrayList 对象(它是从
fromJson()
返回的),但是您试图将它转换为一个数组,并分配给E[] items
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.