简单的: List list = new ArrayList(); Iterator it1 = list1.iterator(); boolean flag = false; while(it1.hasNext() ) { flag=false; User u = (User)it1.next(); Iterator it2 = list2.iterator(); while(it2.hasNext()) { User t = (User)it2.next(); if(t.getId()==u.getId()) { flag=true;//表示已经存在了 break; } } if(!flag) { list.add(u); } }
如果你想使用那个contains()方法就得重写equals()方法 下边是ArrayList中的contain()方法源代码,可以看到它是调用equals()方法去判断两个对像是否相同的. public boolean contains(Object elem) { return indexOf(elem) >= 0; } /** * Searches for the first occurence of the given argument, testing * for equality using the <tt>equals</tt> method. * * @param elem an object. * @return the index of the first occurrence of the argument in this * list; returns <tt>-1</tt> if the object is not found. * @see Object#equals(Object) */ public int indexOf(Object elem) { if (elem == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (elem.equals(elementData[i])) return i; } return -1; }
遍历list1的每一个对像,判断哪一个list2中不包含的.
boolean contains(Object o)
如果列表包含指定的元素,则返回 true。
然后重新放回list中
{
public boolean equals(Object o)
{
if(!(o isintanceof User))
{
return false;
}
if(this==o)
{
return true;
}
User u = (User)o;
if(this.getId()==u.getId())//假设为id基本类型
{
return true;
}
reutrn false;
}
}List list = new ArrayList();//list1中在list2中没有的对像Iterator it1 = list1.iterator();
while(it1.hasNext())
{
Object o = it1.next();
if(! list2.contains(o) )//如果list2中不存这个对像
{
list.add(0);//把list2中不包含的存放到list中
//list1.reomve(o);//根据需要是否移除它
}
}
根据I的值来取就是了
List list = new ArrayList();
Iterator it1 = list1.iterator();
boolean flag = false;
while(it1.hasNext() )
{
flag=false;
User u = (User)it1.next();
Iterator it2 = list2.iterator();
while(it2.hasNext())
{
User t = (User)it2.next();
if(t.getId()==u.getId())
{
flag=true;//表示已经存在了
break;
}
}
if(!flag)
{
list.add(u);
}
}
下边是ArrayList中的contain()方法源代码,可以看到它是调用equals()方法去判断两个对像是否相同的.
public boolean contains(Object elem) {
return indexOf(elem) >= 0;
} /**
* Searches for the first occurence of the given argument, testing
* for equality using the <tt>equals</tt> method.
*
* @param elem an object.
* @return the index of the first occurrence of the argument in this
* list; returns <tt>-1</tt> if the object is not found.
* @see Object#equals(Object)
*/
public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}