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

package collection;
import  java.util.*;

public class NewStudent  implements  Comparable<NewStudent>{
    private int code;
    private String name;
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

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

    public NewStudent(int code, String name, char sex) {
        this.code = code;
        this.name = name;
        this.sex = sex;
    }

    private char sex;


    public NewStudent() {
        super();
    }

    @Override
    public String toString() {
        return "NewStudent{" +
                "code=" + code +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                '}';
    }





    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        NewStudent that = (NewStudent) o;
        return code == that.code &&
                sex == that.sex &&
                Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, name, sex);
    }


    @Override
    public int compareTo(NewStudent o) {
        if (o instanceof NewStudent) {
           NewStudent s = (NewStudent) o;
            if (this.code> s.code)
                return -1;

            if (this.code < s.code)
                return 1;
            return 0;
        }
        throw  new RuntimeException("类型不匹配!!!");
    }
}
package collection;
import java.util.*;

public class Test_NewStudent {
    public static void main(String[] args) {
        //List 中存放若干学生对象(学号,姓名,性别)
        List<NewStudent> list = new ArrayList<>();
        list.add(new NewStudent(12, "小王", '男'));
        list.add(new NewStudent(12, "小张", '女'));
        list.add(new NewStudent(14, "小于", '男'));
        list.add(new NewStudent(14, "小刘", '女'));
        list.add(new NewStudent(16, "小撒", '男'));
        list.add(new NewStudent(17, "小赵", '女'));

       //去除list中重复的元素,并按学号降序输出
        List<NewStudent> studentList = new ArrayList<>(new LinkedHashSet<NewStudent>(list));
        System.out.println("原集合:" + list);
        System.out.println("去重后的集合:" + studentList);
        Collections.sort(studentList, Collections.reverseOrder());
        TreeSet tree = new TreeSet();
        tree.addAll(studentList);
        System.out.println("去重降序后的集合:" + tree);

        }
}









发布了64 篇原创文章 · 获赞 47 · 访问量 9571

猜你喜欢

转载自blog.csdn.net/weixin_42194284/article/details/91911308