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){;
public boolean equals(Object obj){
if(!(obj instanceof Person))
return false;

Person p=(Person)obj;
return && 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();
Person p=(Person);

/*Iterator it=al.iterator();

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

Iterator it=al.iterator();
return newal;
public static void sop(Object 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: