List中存放若干学生对象(学生有学号,姓名,性别等属性),去除List中重复的元素,并按学号降序输出。

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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值