为了账号安全,请及时绑定邮箱和手机立即绑定

可以将 ArrayList<String> 转换为 ArrayList

可以将 ArrayList<String> 转换为 ArrayList

蝴蝶刀刀 2021-08-25 15:17:16
我在 Sharedpreferences 中保存了一些 ArrayList。但是我想在适配器中将我的自定义模型设置为 ArrayList 导致使用 getter 获取项目。我真的厌倦了来自 stackoverflow 的太多解决方案,但我做不到。private ArrayList<String> fullList = new ArrayList<>();到private ArrayList<MyCustom> fullList = new ArrayList<>();我的自定义类:public class InstagramUserSummary implements Serializable {public boolean is_verified;public String profile_pic_id;public boolean is_favorite;public boolean is_private;public String username;public long pk;public String profile_pic_url;public boolean has_anonymous_profile_picture;public String full_name;@Overridepublic int hashCode() {    return Objects.hash(username, pk);}@Overridepublic boolean equals(Object obj) {    if (obj == this) return true;    if (!(obj instanceof InstagramUserSummary)) {        return false;    }    InstagramUserSummary user = (InstagramUserSummary) obj;    return pk == user.getPk();}}列表是这样的:[InstagramUserSummary(super=dev.niekirk.com.instagram4android.requests.payload.InstagramUserSummary@a4acf205, is_verified=false, profile_pic_id=1773528799482591987_1654599017, is_favorite=false, is_private=false, username=ququletta, pk=1654599017, profile_pic_url=https://instagram.fada1-5.fna.fbcdn.net/vp/8d99014623ed527e52512a20002d884b/5C387E45/t51.2885-19/s150x150/31203725_200759604054857_5778864946146181120_n.jpg, has_anonymous_profile_picture=false, full_name=Ququletta)]谢谢。
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

解决方案:


假设您在 MyCustom 类中有一个 String 变量,例如:


public class MyCustom {


    private String strName;


    public MyCustom(String name) {

        this.strName = name;

    }


    public void setName(String name) {

        this.strName = name;

    }


    public String getName() {

         return this.strName;

    }

}

然后,您可以执行以下操作:


for (MyCustom value : fullList) {

    customFullList.add(new MyCustom(value))

}

希望能帮助到你。


查看完整回答
反对 回复 2021-08-25
?
千万里不及你

TA贡献1784条经验 获得超9个赞

首先,没有必要让该username字段成为类的公共成员MyCustom。由于您通过 getter/setter 公开访问该字段是错误的。


除此之外,您可以轻松使用流和映射函数MyCustom从字符串流创建新实例。


为了避免样板代码,我会继续创建一个静态创建者方法,MyCustom如下所示:


public class MyCustom {


    private String userName;

    public String getUserName() { return userName; }

    public void setUserName(String userName) { this.userName = userName; }


    public static MyCustom from(final String userName) {

        MyCustom custom = new MyCustom();

        custom.setUserName(userName);

        return custom;

    }


}

然后我将使用它作为方法引用将字符串转换为 MyCustoms,从而将它们收集到一个新列表中,如下所示:


List<String> list = new ArrayList<>();

List<MyCustom> customs = list.stream()

        .map(MyCustom::from)

        .collect(Collectors.toList());

最后,还要避免使用具体类型初始化列表(例如ArrayList<String> someList = new ArrayList<>;'。对接口进行编码要好得多,因此执行类似List<String> someList = new ArrayList<>.


查看完整回答
反对 回复 2021-08-25
  • 2 回答
  • 0 关注
  • 202 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信