gpt4 book ai didi

java - 从 ArrayList 中删除具有相似值的对象

转载 作者:行者123 更新时间:2023-12-02 03:07:37 25 4
gpt4 key购买 nike

我正在使用 ArrayList ,这里我想从 Arraylist 中删除具有相似值的对象。我尝试了 stackoverflow 上发布的许多解决方案,但由于代码无法正常工作,我的代码出现了问题。我得到了重复的列表。

Here is my code :

public class StateCityModel {

private String id ;
private String code ;
private String name ;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public boolean equals(Object obj) {

if (!(obj instanceof StateCityModel))
return false;

return id.equals(((StateCityModel) obj).getId());

}

@Override
public int hashCode() {
return (id == null) ? 0 : id.hashCode();
}
}

Code add values in the ArrayList

    businessTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView , View view , int position , long l) {
businessTypeObj = clubsList.get(position);
selectedBusinessTypeList.add(businessTypeObj);
}

}
});

Code to remove objects with similar values .

Set<StateCityModel> unique = new LinkedHashSet<StateCityModel>(selectedBusinessTypeList);
selectedBusinessTypeList = new ArrayList<StateCityModel>(unique);

完成上述代码后,我在 selectedBusinessTypeList 中获取具有相似值的对象。

请帮帮我,我找不到上面代码中的错误。

最佳答案

你也可以这样做

第 1 步:仅在 arraylist 中插入 id 不相同的数据,这样之后就不需要从 arraylist 中删除重复元素。

businessTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView , View view , int position , long l) {
businessTypeObj = clubsList.get(position);
selectedBusinessTypeList.add(businessTypeObj);
}

}
});

替换为

businessTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView , View view , int position , long l) {
}

StateCityModel stateCityModel = new StateCityModel();
stateCityModel = clubsList.get(position);;

if (!selectedBusinessTypeList.contains(stateCityModel)){
selectedBusinessTypeList.add(stateCityModel);
}

}

});

第 2 步:删除不需要的内容

Set<StateCityModel> unique = new LinkedHashSet<StateCityModel>(selectedBusinessTypeList);
selectedBusinessTypeList = new ArrayList<StateCityModel>(unique);

关于java - 从 ArrayList 中删除具有相似值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41545375/

25 4 0