import java.util.ArrayList;
Import Java.util.Iterator;
/ * 1. Save the custom object and remove the duplicate elements.
* The 2.List set determines whether the element is the same, based on the Equals method of the element.
* Experience: The Equals method in object determines whether the address value of the object is the same.
* the Equals method in String determines whether the contents of the object are the same.
* in custom classes, make a copy of the Equals method in object to compare the contents of objects.
The variables, objects, and methods that can be encapsulated in Java are encapsulated as far as possible, so that the main function is as concise as possible.
*/
Define a person class
Class person{
//define private variables name and age
private String name;
private int age;
Defines the parameter constructor for the person and initializes the private member variable.
Person (String Name,int age)
{
This.name=name;
This.age=age;
}
The Equals method in the Replication object.
public boolean equals (Object obj)
{
Determines whether the parameter object belongs to the person object
if (! ( obj instanceof person))
return false;
The downward transition allows obj to invoke the member variables in the person.
Person p= (person) obj;
System.out.println (this.name+ "--" +p.name);
Compares name and age, returns true if same, or false
Return This.name.equals (p.name) && (this.age==p.age);
}
//provide external access for private members
Public String GetName ()
{
return name;
}
Provide external access for private members
public int Getage ()
{
return age;
}
}
public class ArrayListDemo1 {
public static void Main (string[] args)
{
Define a container
ArrayList a1=new ArrayList ();
Add a custom object to a container
A1.add (New person ("LISI1", 20));
A1.add (New person ("Lisi2", 21));
A1.add (New person ("Lisi3", 22));
A1.add (New person ("Lisi4", 23));
A1.add (New person ("Lisi3", 22));
A1.add (New person ("Lisi4", 23));
Call method to remove the same element
A1=method (A1);
//Remove elements from the container
SOP (A1.remove ("New Person" ("Lisi3", 22)));
//Define an iterator for A1
Iterator it= a1.iterator ();
to output.
while (It.hasnext ())
{
Person p= (person) it.next ();
SOP (P.getname () + "--" +p.getage ());
}
}
//define method methods
public static ArrayList method (ArrayList li)
{
Define a temporary container
ArrayList newal=new ArrayList ();
//iterator that defines the parameter object
Iterator It=li.iterator ();
while (It.hasnext ())
{
Object Obj=it.next ();
If the temporary container contains no OBJ objects, the object is added
if (!newal.contains (obj))
{
Newal.add (obj);
}
}
return Newal;
}
public static void sop (Object obj)
{
System.out.println (obj);
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Collection (ArrayList exercise)