简体   繁体   English

Android studio ,这不是从共享首选项中检索字符串并将其转换为哈希集的正确方法吗?<string> ?

[英]Android studio , Isnt this the correct way of retrieving a string from shared preferences and casting it to a hashset<string>?

My code is:我的代码是:

HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes" , null);

I got that exception:我得到了那个例外:

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.S

 Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Set
        at android.app.SharedPreferencesImpl.getStringSet(SharedPreferencesImpl.java:293)
        at com.example.notes.MainActivity.onCreate(MainActivity.java:60)

You cannot , under any circumstances, cast a String to a Set (or anything but a type that String directly implements, such as Object , Comparable , or Serializable ).在任何情况下,您都不能将String转换为Set (或String直接实现的类型以外的任何类型,例如ObjectComparableSerializable )。

You must explicitly write code to convert the String to a Set , such as (for example) splitting it on comma characters and adding each element of the split to a set you create.您必须明确编写代码以String转换Set ,例如(例如)将其拆分为逗号字符并将拆分的每个元素添加到您创建的集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM