package Collection;
import java.util.*;
/*
* Save the custom object as an element in the ArrayList collection, and remove duplicate elements
*
* For example: save the object. The same name and age are regarded as the same person and are repeated elements.
*/
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person p=(Person)obj;
return (this.name.equals(p.name)&&this.age==p.age);
}
}
public class ArrayListDemo {
public static void main(String[] args) {
al.add(new Person("lisi02",21));
al.add(new Person("lisi03",22));
al.add(new Person("lisi04",23));
Iterator it=al.iterator();
while(it.hasNext()){
Person p=(Person)it.next(); //向下转型
System.out.println("name: "+p.getName()+" age: "+p.getAge());
}
System.out.println();
while(it1.hasNext()){
Person p=(Person)it1.next();
} public static ArrayList singlement(ArrayList arr){ ArrayList array=new ArrayList(); Iterator it=arr.iterator(); while(it.hasNext()){ Object obj=it.next(); if(!array.contains(obj)){ array.add(obj); } } return array; }
import java.util.*;
/*
* Save the custom object as an element in the ArrayList collection, and remove duplicate elements
*
* For example: save the object. The same name and age are regarded as the same person and are repeated elements.
*/
//Describe the person object and encapsulate the data into the person object
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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person p=(Person)obj;
return (this.name.equals(p.name)&&this.age==p.age);
}
}
public class ArrayListDemo {
public static void main(String[] args) {
//Define the container and store it in the object
ArrayList al=new ArrayList();
al.add(new Person("lisi01",20));al.add(new Person("lisi02",21));
al.add(new Person("lisi03",22));
al.add(new Person("lisi04",23));
Iterator it=al.iterator();
while(it.hasNext()){
Person p=(Person)it.next(); //向下转型
System.out.println("name: "+p.getName()+" age: "+p.getAge());
}
System.out.println();
al=singlement(al);
Iterator it1=al.iterator();while(it1.hasNext()){
Person p=(Person)it1.next();
System.out.println("name: "+p.getName()+" age: "+p.getAge());
}} public static ArrayList singlement(ArrayList arr){ ArrayList array=new ArrayList(); Iterator it=arr.iterator(); while(it.hasNext()){ Object obj=it.next(); if(!array.contains(obj)){ array.add(obj); } } return array; }
}