java removes simple instances of duplicate objects

  • 2020-05-30 20:03:17
  • OfStack

Examples are as follows:


import java.util.*;
class Person {
private String name;
private int age;
Person(String name,int age){
this.name=name;
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 String getName(){
return name;
}
public int getAge(){
return age;
}


}
public class ArrayListTest2{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(new Person("zhangsan1",22));
al.add(new Person("zhangsan2",33));
al.add(new Person("zhangsan3",44));
al.add(new Person("zhangsan5",88));
al.add(new Person("zhangsan4",55));
al.add(new Person("zhangsan1",22));
//al.add(new Person("zhangsan3",44));

al = singelElements(al);
Iterator it1=al.iterator();
while(it1.hasNext()){
Person p=(Person)it1.next();
sop(p.getName()+"..."+p.getAge());
}

/*Iterator it=al.iterator();
while(it.hasNext()){

Person p= (Person)it.next();// I'm going to force it to person type   You can implement the following input otherwise it cannot be called getAge() and getName() methods 
sop(p.getName()+"..."+p.getAge());
}*/
}
public static ArrayList singelElements(ArrayList al){
ArrayList newal=new ArrayList();

Iterator it=al.iterator();
while(it.hasNext()){
Object obj=it.next();
if(!newal.contains(obj))
newal.add(obj);
}
return newal;
}
public static void sop(Object obj){
System.out.println(obj);
}
}

Solution idea: create a temporary container ArrayList to store non-repeating objects. Take the object out twice using an iterator to enter a non-repeating object.

It is important to note that in the Person class you need to define an equals method to compare if there are the same elements. Where instance is used to determine whether an object belongs to that class and if so, return true or false.

Note that in Java programming ArrayLis and other containers call contains and remove methods when they call equals methods. This is one of the things that a lot of people don't pay attention to.


Related articles: