【发布时间】:2014-06-18 12:35:30
【问题描述】:
我想从 Alerts 类型的 ArrayList 中删除重复项,其中 Alerts 是一个类。
班级提醒 -
public class Alerts implements Parcelable {
String date = null;
String alertType = null;
String discription = null;
public Alerts() {
}
public Alerts(String date, String alertType, String discription) {
super();
this.date = date;
this.alertType = alertType;
this.discription = discription;
}
}
这是我添加元素的方式 -
ArrayList<Alerts> alert = new ArrayList<Alerts>();
Alerts obAlerts = new Alerts();
obAlerts = new Alerts();
obAlerts.date = Date1.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
obAlerts = new Alerts();
obAlerts.date = Date2.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
我想从中删除的内容-
我想要所有具有唯一 obAlerts.date 和 obAlerts.alertType 的警报。换句话说,删除重复的obAlerts.date 和obAlerts.alertType 警报。
我试过了 -
Alerts temp1, temp2;
String macTemp1, macTemp2, macDate1, macDate2;
for(int i=0;i<alert.size();i++)
{
temp1 = alert.get(i);
macTemp1=temp1.alertType.trim();
macDate1 = temp1.date.trim();
for(int j=i+1;j<alert.size();j++)
{
temp2 = alert.get(j);
macTemp2=temp2.alertType.trim();
macDate2 = temp2.date.trim();
if (macTemp2.equals(macTemp1) && macDate1.equals(macDate2))
{
alert.remove(temp2);
}
}
}
我也试过-
HashSet<Alerts> hs = new HashSet<Alerts>();
hs.addAll(obAlerts);
obAlerts.clear();
obAlerts.addAll(hs);
【问题讨论】:
-
您希望每个对象有一个不同的
date和一个不同的alertType。因此,如果dateORalertType对于两个对象相同,则必须删除该对象。 -
@G.T.是的。如何删除此类重复项?
-
和你一样。只需在最后一个
if中将&&替换为||。
标签: android arraylist hashset linkedhashset