リスト内の異なる要素を特定し、2つのリスト内の同じオブジェクトを削除します.


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();
	}


}