两个list,都放了几百个int型数删除连个list当中相同的数字。求思路。说个最容易想到的吧:
listA
listB Iterator<Integer> it = listA.iterator();
while (it.hasNext()) {
int tmp = it.next();
if (listB.contains(tmp)) {
listB.remove(listB.indexOf(tmp));
it.remove();
}
}有更好的方法吗?

解决方案 »

  1.   

    放setlist l1 = new arraylist();
    collections.addAll(l1,1,2,3,4,5);list l2 = new arraylist();
    collections.addAll(l1,1,6,7,4,5);set s =new hashset();
    s.addAll(l1);
    s.addAll(l2);s里就是没有重复的……
      

  2.   

    哦哦 有个错list l2 = new arraylist();
    collections.addAll(l2,1,6,7,4,5);
      

  3.   

    光从循环逻辑来说,我觉得LZ的方法已经足够好了。有一点小改的地方。
    能避免使用listB.indexOf(tmp),
    把listB.remove(listB.indexOf(tmp));
    改成
    listB.remove((Object) tmp);
    应该可以提高点效率。当然使用泛型更直观。
    List<Integer> listA = new ArrayList<Integer>();
    List<Integer> listB = new ArrayList<Integer>(); listA.add(1);
    listA.add(2);
    listA.add(3); listB.add(2);
    listB.add(3);
    listB.add(6); Iterator<Integer> it = listA.iterator();
    while (it.hasNext()) {
    int tmp = it.next();
    if (listB.contains(tmp)) {
    listB.remove(new Integer(tmp));
    it.remove();
    }
    }
      

  4.   

    楼主不知道想没想过重复的现像怎么办。
    比如你的LISTA里面有两个2,LISTB中有一个。2
    你的第一次循环会删掉A的1个2.和B的2.
    那到第二个2怎么办。
      

  5.   

    \这是个好问题,但从这个问题来说确实应该考虑。不过我的这两个list都是数据库主键里拿出来的,所以不会有重复。