测试的实体类的代码如下
package com.zk.entity;
import java.util.Date;
public class Student {
private String id;
private String name;
private int age;
private Date birth;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Student(String id, String name, int age, Date birth) {
super();
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", birth=" + birth + "]";
}
public static void main(String[] args) {
Date date = new Date();
Student s = new Student("123", "zhangsan", 11, date);
System.out.println(s.toString());
}
}
测试类的代码块如下:
package com.zk.test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.zk.entity.Student;
/**
* 测试泛型list去重复的方法*/
public class ListTest {
public static void main(String[] args) {
Date date = new Date();
Student s1 = new Student("123", "张三", 11, date);
Student s2 = new Student("1234", "张三1", 12, date);
Student s3 = new Student("123", "张三", 13, date);
Student s4 = new Student("1235", "张三", 14, date);
Student s5 = new Student("12", "张三", 15, date);
Student s6 = new Student("123", "张三", 16, date);
List<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
//list.add(s1);
List<Student> list1 = new ArrayList<Student>();
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
int n=0;//作为一个判断依据,如果n=1,表示存在重复的对象(这里指的的id相同)
for (int j = i+1; j < list.size(); j++) {
//判断i和j对应对象的id是否相等
if(list.get(i).getId().equals(list.get(j).getId())) {
n = 1;
break;
}
}
//判断i对应的对象在list中有没有重复的,如果没有的话就存起来
if(n != 1) {
list1.add(list.get(i));
}
}
System.out.println("新的list的长度为:"+list1.size());
for (int i = 0; i < list1.size(); i++) {
System.out.println(list1.get(i).toString());
}
}
}
测试的结果如下:
重点在于测试代码中的for循环