A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 纪艺松 中级黑马   /  2012-7-30 09:42  /  1609 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 纪艺松 于 2012-7-30 13:10 编辑

import java.util.*;
class Person{
private int id;
Person(int id){
  this.id = id;
}
boolean equals(Person p){
  return this.id == p.id;
}
public String toString(){
   
  return "person"+"("+id+")";
}
}
class ex2 {
public static void main(String[] args){
  List<Person> li = new LinkedList<Person>();
  List<Person> li1 = new LinkedList<Person>();
  for(int i=0; i<10; i++){
   li.add(new Person(i));
  }
  System.out.println("之前完整集合li");
  System.out.println(li);
  
  li1 = li.subList(2, 5);
  System.out.println("sub集合li1");
  System.out.println(li1);
  /*
  for(Person p : li){
   for(Person p1 : li1){
    if(p.equals(p1))
     li.remove(p);
   }
  }*/
  
  /*
  for(int i=0; i<li.size(); i++){
   for(int j=0; j<li1.size(); j++){
    if(li.get(i)==li1.get(j))
     li.remove(i);
   }
  }
  */
  
  Iterator<Person> it = li.iterator();
  Iterator<Person> it1 = li1.iterator();
  while(it.hasNext()){
   while(it1.hasNext()){
    if(it.next()==it1.next()){
     it.remove();
    }
   }
  }
  System.out.println("去除后的集合");
  System.out.println(li);
  
  
}
}
三种好像都不行。。。

1 个回复

倒序浏览
是可以使用removeAll()方法的,我帮你修改的就用了这个方法
  1. import java.util.*;

  2. class Person {
  3.         private int id;

  4.         Person(int id) {
  5.                 this.id = id;
  6.         }

  7.         boolean equals(Person p) {
  8.                 return this.id == p.id;
  9.         }

  10.         public String toString() {

  11.                 return "person" + "(" + id + ")";
  12.         }
  13. }

  14. class ex2 {
  15.         public static void main(String[] args) {
  16.                 List<Person> li = new LinkedList<Person>();
  17.                 List<Person> li1 = new LinkedList<Person>();
  18.                 for (int i = 0; i < 10; i++) {
  19.                         li.add(new Person(i));
  20.                 }
  21.                 System.out.println("之前完整集合li");
  22.                 System.out.println(li);

  23.                 li1 = li.subList(2, 5);
  24.                 System.out.println("sub集合li1");
  25.                 System.out.println(li1);
  26.                 /*
  27.                  * for(Person p : li){ for(Person p1 : li1){ if(p.equals(p1))
  28.                  * li.remove(p); } }
  29.                  */

  30.                 /*
  31.                  * for(int i=0; i<li.size(); i++){ for(int j=0; j<li1.size(); j++){
  32.                  * if(li.get(i)==li1.get(j)) li.remove(i); } }
  33.                  */
  34.                 li1.removeAll(li);//修改的地方是这里
  35.                 System.out.println("去除后的集合");
  36.                 System.out.println(li);

  37.         }
  38. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马