package DailyWork;
import java.util.*;
/**
- List中存放若干学生对象(学生有学号,姓名,性别等属性),去除List中重复的元素,并按学号降序输出。
*/
class Student implements Comparable{
private int age;
private int id;
private String name;
private char sex;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && sex == student.sex && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, sex);
}
public Student(int id, String name, char sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sex=" + sex + '}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
@Override
public int compareTo(Object o) {
if (o instanceof Student){
Student s = (Student) o;
if (this.id >= s.id) {
return -1;
}
if (this.id < s.id) {
return 1;
}
}
throw new RuntimeException("只能和学生类型的对象比较大小!");
}
}
public class DayJune {
public static void main(String[] args) {
List s = new ArrayList();
s.add(new Student(12,"A",'M'));
s.add(new Student(12,"A",'M'));
s.add(new Student(13,"B",'F'));
s.add(new Student(10,"A",'M'));
System.out.println("排序前:");
System.out.println(s);
Collections.sort(s); //值得注意的是 因为比较的是id值,而 在设置比较标准的时候应该出现 ‘=’情况
System.out.println("排序后:");
System.out.println(s);
//有关list转化成Linkedhashset,采取一个一个放进去,而不是 a=s
LinkedHashSet a = new LinkedHashSet ();
for (int i=0; i<s.size(); i++)
{
a.add(s.get(i));
}
System.out.println("根据set集合的互异性,筛选后的结果:");
System.out.println(a);
}
}