day14-11
List集合看元素是否相同,依据是元素的方法
比较的是对象,
ArrayList
存对象,就是把一人,包含姓名,年龄
每调一次contains,contains就要调equals,我们把原杀了
要知道,存的是地址。
package test.bixiangdong;
import java.util.ArrayList;
import java.util.Iterator;
class Person{
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getage(){
return age;
}
public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person p=(Person) obj;
System.out.println(p.name+"---"+this.name);
return (this.name.equals(p.name)) && (this.age==p.age);
}
}
public class Test {
public static ArrayList singleElement(ArrayList al){
ArrayList alNew=new ArrayList();
Iterator it=al.iterator();
while(it.hasNext()){
Object obj=it.next();
if(!alNew.contains(obj)){
//alNew.add(it.next());//NoSuchElementException ——————————next()一定要注意,因为你取了二次,最后一次必为空
alNew.add(obj);
}
}
return alNew;
}
public static void sop(Object obj){
System.out.println(obj);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t=new Test();
ArrayList al=new ArrayList();
al.add(new Person("java1",30));
al.add(new Person("java2",30));
al.add(new Person("java1",40));
al.add(new Person("java3",30));
al.add(new Person("java3",30));
al=t.singleElement(al);
Iterator it2=al.iterator();
while(it2.hasNext()){
Person p2=(Person)it2.next();
sop("no repeat:"+p2.getName()+"---"+p2.getage());
}
//kill a element
sop("remove java3"+al.remove(new Person("java1",30)));
}
}
java1---java2
java1---java1
java2---java1
java1---java3
java2---java3
java1---java3
java1---java3
java2---java3
java1---java3
java3---java3
no repeat:java1---30
no repeat:java2---30
no repeat:java1---40
no repeat:java3---30
java1---java1
remove java3true