package com.heima;
import java.util.ArrayList;
import java.util.Iterator;
@SuppressWarnings("rawtypes")
public class test1 {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("黑马",100));
list.add(new Person("黑马",100));
list.add(new Person("传智",100));
list.add(new Person("传智",100));
list.add(new Person("博客",100));
ArrayList newList = getSingle(list);
System.out.println(newList);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ArrayList getSingle(ArrayList list) {
ArrayList newList = new ArrayList<>();
Iterator it = list.iterator();
while (it.hasNext()) {
Person p = (Person)it.next();
if (!newList.contains(p)) {
newList.add(p);
}
}
return newList;
}
}
package com.heima;
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
}
|
|