黑马程序员技术交流社区
标题:
去除ArrayList中重复的元素
[打印本页]
作者:
xiaoya0o0o
时间:
2015-9-21 22:16
标题:
去除ArrayList中重复的元素
import java.util.ArrayList;
import java.util.List;
/*
* 去除ArrayList中重复的元素:
*
* 以下两种方式都需要掌握:
*
* 方式一:定义一个新集合;
* 方式二:遍历当前集合,在当前集合的基础上进行修改;
*/
public class Demo {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Student("李四",22));
list.add(new Student("李四",22));
list.add(new Student("李四",22));
list.add(new Student("张三",20));
list.add(new Student("李四",22));
list.add(new Student("李四",22));
list.add(new Student("王五",24));
list.add(new Student("王五",24));
list.add(new Student("王五",24));
list.add(new Student("王五",24));
list.add(new Student("王五",24));
/*
//方式一:
List newList = new ArrayList();
//遍历
loop:
for(int i = 0;i < list.size() ;i++){
Student stu = (Student)list.get(i);
for(int j = 0;j < newList.size() ; j++){
Student stu2 = (Student)newList.get(j);
if(stu.equals(stu2)){
continue loop;
}
}
//将stu添加到newList中
newList.add(stu);
}
//遍历newList
for(int i = 0 ;i < newList.size() ; i++){
Student stu = (Student)newList.get(i);
System.out.println(stu.name + "," + stu.age);
}*/
//方式二:
for(int i = 0; i < list.size() - 1 ; i++){
Student stu1 = (Student)list.get(i);
for(int j = i + 1 ; j < list.size() ; j++){
Student stu2 = (Student)list.get(j);
if(stu1.equals(stu2)){
list.remove(j);
j--;
}
}
}
//遍历原集合
for(int i = 0; i < list.size() ; i++){
Student stu = (Student)list.get(i);
System.out.println(stu.name + "," + stu.age);
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2