zoukankan      html  css  js  c++  java
  • [Java] 对象排序示例

    package test.collections;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.List;
    
    public class Test02 {
        public static void main(String[] args){
            List<Song> songs = new ArrayList<Song>();
            songs.add(new Song(2,"黄家驹","光辉岁月"));
            songs.add(new Song(5,"刘德华","忘情水"));
            songs.add(new Song(44,"张学友","吻别"));
            songs.add(new Song(32,"刘德华","爱你一万年"));
            songs.add(new Song(123,"黄家驹","冷雨夜"));
            songs.add(new Song(133,"小虎队","爱"));
            
            Collections.sort(songs);
            printList(songs);
        }
        public static void printList(Collection<Song> c){
            for(Song song:c){
                System.out.println(song);
            }
        }
    }
    class Song implements Comparable<Song>{
        private String name;
        private String songer;
        private int id;
        public Song(int id,String songer,String name) {
            super();
            this.id = id;
            this.name = name;
            this.songer = songer;
        }
        
        @Override
        public String toString() {
            return "Song [name=" + name + ", songer=" + songer + ", id=" + id + "]";
        }
    
        public Song() {
            super();
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSonger() {
            return songer;
        }
        public void setSonger(String songer) {
            this.songer = songer;
        }
        public int compareTo(Song s){
            //使用this.id 和s.id做比较,如果返回值>1,表示顺序排序,返回值是<1的数表示倒序
            if(this.id>s.id){
                return 1;
            }else if(this.id<s.id){
                return -1;
            }else {
                return 0;
            }
            
            //根据歌名排序
            //return this.getName().compareTo(s.getName());
            //根据歌手名排序
            //return this.getSonger().compareTo(s.getSonger());
        }
    }
  • 相关阅读:
    mac 使用brew 安装php-redis
    thinkphp6 使用redis 实现消息队列
    Redis 桌面管理器:Another Redis Desktop Manager
    linux 查看并关闭shell脚本执行
    MySQL教程之concat以及group_concat的用法
    PHP redis 使用
    thinkphp6 command(自定义指令)
    git 使用
    linux shell中 "2>&1"含义
    linux crontab 定时任务
  • 原文地址:https://www.cnblogs.com/frost-yen/p/5383325.html
Copyright © 2011-2022 走看看