- package com.test;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.List;
- /**
- *
- * 找出两个list中不同的元素
- * @author leiwei 2011-12-14
- *
- */
- public class NoEqualsElement {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- list1.add("1");
- list1.add("3");
- list1.add("8");
- list1.add("9");
- list2.add("2");
- list2.add("3");
- list2.add("7");
- for(String s2:list1) {
- boolean flag = false;
- for(String s1:list2) {
- if(s2.equals(s1)) {
- flag = true;
- break;
- }
- }
- if(!flag){
- System.out.println(s2);
- }
- }
- }
- }
- package com.test;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Set;
- import com.model.Student;
- /**
- * 重写对象Student的equals方法
- * 只要age相等 对象就相等
- *
- * 删除两个集合中 相同的对象只保留一个
- * @author leiwei 2011-12-19
- *
- */
- public class ListOBJ {
- public static void main(String[] args) {
- Set<Student> setStudent = new HashSet<Student>();
- List<Student> list1 = new ArrayList<Student>();
- List<Student> list2 = new ArrayList<Student>();
- Student s1 = new Student();
- s1.setAge("10");
- list1.add(s1);
- Student s2 = new Student();
- s2.setAge("20");
- list1.add(s2);
- Student s3 = new Student();
- s3.setAge("20");
- list2.add(s3);
- Student s4 = new Student();
- s4.setAge("30");
- list2.add(s4);
- /**
- * 我们知道set集合,中的元素不会重复
- *
- * 将连个对象集合放进去,自然就会排出重复的
- *
- * 对象(前提Student 对象重写了equals方法)
- */
- setStudent.addAll(list1);
- setStudent.addAll(list2);
- //输出 测试看是否 排出成功
- System.out.println(setStudent.size());
- Iterator<Student> iterator = setStudent.iterator();
- while (iterator.hasNext()) {
- Student s = iterator.next();
- System.out.println(s.getAge());
- }
- }
- }
- package com.model;
- public class Student {
- private String age;
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- //重写equals方法只要age相等,我们就认为对象两个相等
- @Override
- public boolean equals(Object obj) {
- if(obj instanceof Student){
- Student st=(Student) obj;
- return (age.equals(st.age));
- }else{
- return super.equals(obj);
- }
- }
- @Override
- public int hashCode() {
- return age.hashCode();
- }
- }
转自:http://blog.****.net/goodleiwei/article/details/7083199