Package com.test;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.Collections;
Import java.util.List;
/**
*
Find out the different elements of the two 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; /** * Overriding object student equals method * As long as the age equality object is equal * * Delete the same object in two collections only one * @author leiwei 2011-12-19 * */public class Li
stobj {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); /** * We know the set set, the elements in the will not repeat * * will be a set of objects into the collection, will naturally emit duplicate * * Object (if student object overrides the Equals method)/Setstudent.adda
ll (List1);
Setstudent.addall (LIST2); Output test to see if successful 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;
}
Overriding the Equals method as long as the age is equal, we consider the object two equal
@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 ();
}
}