码迷,mamicode.com
首页 > 编程语言 > 详细

使用Collections 将自定义对象进行排序

时间:2020-02-13 19:12:56      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:static   his   out   string   class   length   public   div   lis   

对象排序或比较的场合均需要Comparable接口

public class  User implements Comparable<User>{
    private String name;
    private int phone;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }    
    public int getPhone() {
        return phone;
    }
    public void setPhone(int phone) {
        this.phone = phone;
    }
    public String toString() {
        
        return name+"  "+phone;
    }
    User(String name ,int phone)
    {
        this.name=name;
        this.phone=phone;
    }
    public int compareTo(User anotherString) {
        int len1 = this.getName().length();
        int len2 = anotherString.getName().length();
        int lim = Math.min(len1, len2);
        char v1[] = this.getName().toCharArray();
        char v2[] = anotherString.getName().toCharArray();

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }    
}
import java.util.*;
public class Test{
    public static void main(String[] args){
        List l =new ArrayList();
        l.add(new User("a",456123));
        l.add(new User("e",888123));
        l.add(new User("uuu",45993));
        l.add(new User("oo",33123));
        Collections.sort(l);
        System.out.println(l);
    }
}

技术图片

使用Collections 将自定义对象进行排序

标签:static   his   out   string   class   length   public   div   lis   

原文地址:https://www.cnblogs.com/When6/p/12304481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!