package com.test;
import java.util.*;
class User{
public String name;
public Integer age;
public boolean equals(Object obj) {//重写 对比函数
if(obj instanceof User) {
User u = (User)obj;
return this.name.equals(u.name) && this.age.equals(u.age);
}
return super.equals(obj);
}
}
public class Demo1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
ArrayList<User> list = new ArrayList<>();
// 开启后报错
// for(int i = 1; i <= 3; i++) {
// Scanner scanner = new Scanner(System.in);
// User user = new User();
// System.out.println("请输入用户信息");
// System.out.println("姓名");
// user.name = scanner.nextLine();
// System.out.println("密码");
// user.age = scanner.nextInt();
// list.add(user);
// scanner.close();
// }
// 普通 1
Scanner scanner = new Scanner(System.in);
User user_a = new User();
User user_b = new User();
User user_c = new User();
System.out.println("请输入用户信息");
System.out.println("姓名");
user_a.name = scanner.nextLine();
System.out.println("密码");
user_a.age = scanner.nextInt();
list.add(user_a);
//System.out.println("请输入用户信息");
System.out.println("姓名");
user_b.name = scanner.nextLine();
System.out.println("密码");
user_b.age = scanner.nextInt();
list.add(user_b);
//System.out.println("请输入用户信息");
System.out.println("姓名");
user_c.name = scanner.nextLine();
System.out.println("密码");
user_c.age = scanner.nextInt();
list.add(user_c);
scanner.close();
// 普通2
User user1 = new User();
user1.name = "景山";
user1.age = 33;
list.add(user1);
User user2 = new User();
user2.name = "景山";
user2.age = 23;
list.add(user2);
User user3 = new User();
user3.name = "景山";
user3.age = 23;
list.add(user3);
// 输出信息
Iterator<User> iterator = list.iterator();
while(iterator.hasNext()) {
User u = (User)iterator.next();
System.out.println(u.name);
System.out.println(u.age);
}
System.out.println("去掉重复后的结果");
// 手工去掉重复
List<User> list1 = getList(list);
Iterator<User> iterator1 = list1.iterator();
while(iterator1.hasNext()) {
User u = (User)iterator1.next();
System.out.println(u.name);
System.out.println(u.age);
}
}
// 去重函数
public static List<User> getList(List<User> list) {
List<User> listCopy = new ArrayList<User>();
Iterator<User> iterator = list.iterator();
while(iterator.hasNext()) {
User u = (User)iterator.next();
if(!listCopy.contains(u)) {
listCopy.add(u);
}
}
return listCopy;
}
}