您的位置:首页 > 其它

List 去掉对象元素

2014-04-22 19:27 253 查看
经常需要将List中重复元素去掉,或者判断两个List中相同的元素。

1、通过set接口,set 不包含满足
e1.equals(e2)


HashSet set = new HashSet(list2);
list2.clear();
list2.addAll(set);


2、普通方法,每个元素在List中进行比较

for (int i = 0; i < list.size() - 1; i++)
{
for (int j = list.size() - 1; j > i; j--)
{
if (list.get(j).equals(list.get(i)))
{
list.remove(j);
}
}
}


3、还是通过Set 接口

Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();)
{
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);


如果是对象元素,必须重写eauals方法和hashCode方法

例如:

@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}

if (obj instanceof UserQuestion)
{
UserQuestion userQuestion = (UserQuestion)obj;

if (userQuestion.userId == this.userId)
{
return true;
}
}

return false;
}

@Override
public int hashCode()
{
String in = userId + sumPassId + sumPassId + questionId + "";

return in.hashCode();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: