zoukankan      html  css  js  c++  java
  • 怎么给list内的对象排序?

    首先,对象要实现Comparable接口,自然需要重写compareTo方法

    在compareTo里定义哪个排前面,中间就是return 0

    compareTo方法中要确定:

    1.拿哪个属性比较

    2.怎么样就可以排在前面

    3.排在前面返回1,排在后面返回-1

    public class Employee implements Comparable<Employee>{
        private int id;
        private String name;
        private int age;
        public Employee(int id,String name,int age){
            this.id = id;
            this.name = name;
            this.age = age;
        }
        @Override
        public int compareTo(Employee o) {
    
            if(id > o.getId()){
                return 1;
            }else if(id < o.getId()){
                return -1;
            }
            
            return 0;
        }
        /**
         * @return the id
         */
        public int getId() {
            return id;
        }
        /**
         * @param id the id to set
         */
        public void setId(int id) {
            this.id = id;
        }
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
        /**
         * @return the age
         */
        public int getAge() {
            return age;
        }
        /**
         * @param age the age to set
         */
        public void setAge(int age) {
            this.age = age;
        }
        /* (non-Javadoc)
         * @see java.lang.Object#toString()
         */
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("员工编号:"+getId()+",");
            sb.append("员工姓名:"+getName()+",");
            sb.append("员工年龄:"+getAge());
            return sb.toString();
        }
        

    list内对象的排序:

    1.声明list

    2.添加元素

    3.用Collections.sort(list);方法完成排序

    public static void main(String[] args) {
            
            List<Employee> list = new ArrayList<Employee>();
            list.add(new Employee(3,"王志",21));
            list.add(new Employee(2,"李农",22));
            list.add(new Employee(1,"郭楠",23));
            //先遍历,在遍历中打印每个对象
            System.out.println("排序前:");
            for(Employee e : list){
                System.out.println(e);
            }
            Collections.sort(list);
            System.out.println("排序后:");
            for(Employee e : list){
                System.out.println(e);
            }
            
            
            
            
        }

  • 相关阅读:
    对JAVA集合进行遍历删除时务必要用迭代器
    【javascript的那些事】等待加载完js后执行方法
    【微信H5】 Redirect_uri参数错误解决方法
    关于Java优质代码的那些事
    H5页面微信分享和手Q分享设置
    LVS+keepalived-DR模式
    Linux文件误删恢复
    MySQL常用语句
    sudo权限配置
    Rsync同步部署web服务端配置
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5573432.html
Copyright © 2011-2022 走看看