Java comparable接口 对象排序

前面写了一篇文章是关于comparator的,那么comparable就必须拿出来做了分析对比。

关于这俩个接口的文章也比较多,本文着重从完整的代码示例去展现说明。

OK

首先,还是看下Comparator这里接口的代码:

public interface Comparable<T> {
    /**
     * Compares this object with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     *
     * <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
     * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
     * implies that <tt>x.compareTo(y)</tt> must throw an exception iff
     * <tt>y.compareTo(x)</tt> throws an exception.)
     *
     * <p>The implementor must also ensure that the relation is transitive:
     * <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
     * <tt>x.compareTo(z)>0</tt>.
     *
     * <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
     * implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
     * all <tt>z</tt>.
     *
     * <p>It is strongly recommended, but <i>not</i> strictly required that
     * <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>.  Generally speaking, any
     * class that implements the <tt>Comparable</tt> interface and violates
     * this condition should clearly indicate this fact.  The recommended
     * language is "Note: this class has a natural ordering that is
     * inconsistent with equals."
     *
     * <p>In the foregoing description, the notation
     * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
     * <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
     * <tt>0</tt>, or <tt>1</tt> according to whether the value of
     * <i>expression</i> is negative, zero or positive.
     *
     * @param   o the object to be compared.
     * @return  a negative integer, zero, or a positive integer as this object
     *          is less than, equal to, or greater than the specified object.
     *
     * @throws NullPointerException if the specified object is null
     * @throws ClassCastException if the specified object's type prevents it
     *         from being compared to this object.
     */
    public int compareTo(T o);
}

只有一个方法,compareTo(T o),没啥好说的,简单哈

现在,给出实现该接口的一个示例:(注意在其中的注释说明了这俩个接口的用途)

package someTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class ComparablePerson implements Comparable<Object> {
     String firstName,lastName;
     Boolean Sex;
     Integer age;
    public ComparablePerson(String firstName, String lastName,Boolean Sex, Integer age){
        this.firstName = firstName;
        this.lastName  = lastName;
        this.Sex       = Sex;
        this.age       = age;
    }
    public String getFirstName() {  
         return firstName;  
       }  
      
       public String getLastName() {  
         return lastName;  
       }  
       public Boolean getSex() {  
          return Sex;  
        }  
      
        public Integer getAge() {  
          return age;  
        }  
      //为了输入方便,重写了toString()  
  public String toString()  
       {  
          return firstName +" "+lastName+" "+(Sex.booleanValue()?"男":"女")+" "+age;  
       }  
    //定义比较方法
    public int compare(Object o1, Object o2){  
        if (o1 instanceof String) {  
          
            return compareImp( (String) o1, (String) o2);  
          
        }else if (o1 instanceof Integer) {  
            
          return compareImp( (Integer) o1, (Integer) o2);  
          
        }else if (o1 instanceof Boolean) {  
            
        return compareImp( (Boolean) o1, (Boolean) o2);  
        
        }else {  //根据需要扩展compare函数
          System.err.println("未找到合适的比较器");  
          return 1;  
        }  
      }  
    //重载  
public int compareImp(String o1, String o2) {  
        String s1 = (String) o1;  
        String s2 = (String) o2;  
        int len1 = s1.length();  
        int len2 = s2.length();  
        int n = Math.min(len1, len2);  
        char v1[] = s1.toCharArray();  
        char v2[] = s2.toCharArray();  
        int pos = 0;  
 
        while (n-- != 0) {  
          char c1 = v1[pos];  
          char c2 = v2[pos];  
          if (c1 != c2) {  
            return c1 - c2;  
          }  
          pos++;  
        }  
        return len1 - len2;  
      }  
    //重载  
public int compareImp(Integer o1, Integer o2) {  
        int val1 = o1.intValue();  
        int val2 = o2.intValue();  
        return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));  
 
      }
    //重载
public int compareImp(Boolean o1, Boolean o2) {  
      return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1));  
     }  
 
    @Override
    public int compareTo(Object o){
        ComparablePerson p = (ComparablePerson)o;
         String firstname1 = p.getFirstName();  
         String lastname1 = p.getLastName();  
         Boolean sex1 = p.getSex();  
         Integer age1 = p.getAge();  
            
         int compareFirstName = compare(this.firstName, firstname1);
         int compareLastName = compare(this.lastName, lastname1);
         int compareSex = compare(this.Sex, sex1);

            if (compareFirstName != 0) {
                return compareFirstName;
            }

            if (compareLastName != 0) {
                return compareLastName;
            }

            if (compareSex != 0) {
                return compareSex;
            }

            return compare(this.age, age1);  
    }
    
    public static void main(String[] args) {
        ComparablePerson p1 = new ComparablePerson("zangwu","gg",false,27);
        ComparablePerson p2 = new ComparablePerson("zhangsan","gg",false,21);
        int res = p1.compareTo(p2);
       /*Returns a
        * negative integer, zero, or a positive integer as this object is less
        * than, equal to, or greater than the specified object.
        */
        System.out.println(res);
        
        /*
         * Comparable接口和Comparator接口的不同,就是具体实现方法的不同
         * 具体在实现方法中,要根据比较类的那个字段排序,由程序员自己编写
         * Comparable接口的特点就是在CompareTo(Object o)方法,如果你是比较的类的编写者,就可以在要排序的类上实现
         * 该接口;这就是它的特别之处;
         * 在有些情况下,这个类你仅仅能调用,那么你就需要在自己的编写的类上实现Comparator接口,用 int compare(Object o1, Object o2)
         * 方法来实现待比较的类实例对象的一个比较。
         * 这就是很多人说的Comparable是内部的比较器,Comparator是外部的比较器。*/
        ArrayList<ComparablePerson> list = new ArrayList<ComparablePerson>();
               // 添加对象到ArrayList中
              list.add(new ComparablePerson("ccc", "aaa",true,20));
              list.add(new ComparablePerson("AAA","bbb",true,30));
              list.add(new ComparablePerson("ccc", "aaa",false,10));
              list.add(new ComparablePerson("ccc","aaa",false, 40));
       
               // 打印list的原始序列     
        System.out.println("排序前:");
            for (Iterator<ComparablePerson> iter = list.iterator(); iter.hasNext();){    
                 ComparablePerson Person =(ComparablePerson)iter.next();
                 System.out.println("before sort=" +Person);  
              }  
        
               // 对list进行排序
               // 这里会根据“ComparablePerson实现的Comparable<Object>接口”进行排序,即会根据compareTo(Object o)进行排序
        Collections.sort(list);
            for (int i = 0; i < list.size(); i++) {
                if(i==0)
                 System.out.println("排序后:");
                 System.out.println("after sort=" + list.get(i));  
             }  
    }
}

个人意见,欢迎交流。

Java comparable接口 对象排序

时间: 2024-08-11 09:56:11

Java comparable接口 对象排序的相关文章

Java集合中对象排序

集合中的对象排序需求还是比较常见的,当然我们可以重写equals方法,循环比较:同时Java为我们提供了更易使用的APIs.当需要排序的集合或数组不是单纯的数字型时,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序. 下面通过两个例子分别用Comparable和Comparator实现对User对象中年龄排序. Comparable接口方式 类自身实现Comparable接口,实现该接口中的compareTo方法. import java.util.A

Comparable接口比较排序 示例

package cn.caijiajia.campaignnew.job; import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Book implements Comparable{ /*编写一个类Book,具有name,price,press,author属性.然后创建5个对象放入ArrayList中,并实现按照price大小排序(使用Comparable接口排序)

java中的类实现comparable接口 用于排序

import java.util.Arrays; public class SortApp { public static void main(String[] args) { Student[] stus = new Student[3]; stus[0] = new Student(11, 99); stus[1] = new Student(13, 92); stus[2] = new Student(13, 89); Arrays.sort(stus); for (Student stu

Java中比较对象大小的两种实现方式

引入原因: Java中的对象,正常情况下,只能进行比较:== 或!= ,不能使用 < 或 > ,但是在开发时需要用到比较对象的大小 1.Comparable接口的使用(自然排序) 1.像String .包装类等实现了Comparable接口,重写了compareTo()方法,给出了比较两个对象大小的方法 2.像String .包装类等重写了compareTo()方法后,默认执行了从小到大的排序 3.重写compareTo()的规则: 如果当前对象this大于形参对象obj,则返回正整数,如果当

Comparable接口与Comparator接口的比较————总结

之前的两篇文章主要学习了Comparable接口和Comparator接口的学习.既然已经学习完了,现在就趁热打铁,进行总结吧! Comparable接口和Comparator接口的共同点: 1. 都是为了进行排序.(废话,当然都是进行排序了!!!嘿嘿,大家都能看出来,不过还是写下来了!) 2. 都是接口.(额..又是废话) 除此之外,小编想不出还有什么共同点了!想到了其他的相同点可以在文章下方留言,大家一起学习! 相同点说完了,接下来就是不同点啦. Comparable接口与Comparato

关于Comparable接口的使用

一.使用Comparable接口进行排序:如何要都某种数据类型或者是自定义的类进行排序必须要实现Comparable jdk定义的基本数据类型和String类型的数据都实现了Comparable.下面以实例来展现Comparable的具体实现 1.Comparable接口的定义: public interface Comparable<T> { public int compareTo(T o); } Comparable接口只定义了一个方法compareTo(T o):返回int类型的数据.

java中的排序Comparable接口和Comparator接口

普通的类要实现排序,必须实现Comparable接口,并重写CompareTo()方法. package test; public class Field implements Comparable<Field> {     private String name;     private int age;     public Field() {     }     public Field(String name, int age) {         this.name = name;

java集合中对象某属性比较排序Comparable与Comparator

要对集合中的对象的某属性进行排序有两种方式. a. 一种是要排序对象类实现comparable接口的compareTo方法:然后把对象放入list:然后调用Collections.sort(list);b. 一种是不对要排序对象类做任何改动,创建Comparator接口的实现类C:然后 把对象放入list:然后调用Collections.sort(list, C); a.eg ---------------------------------- 1 public class User imple

【LeetCode】two num 利用comparable接口 对对象进行排序

题目two num 题意:给定一个整数数组和一个目标值,要求在数组中找到两个数,使得它们的和相加等于目标值,并且返回两个数的下标 思路:1.如果使用暴力,时间复杂度为O(n^2) 2.可以先将所有数进行排序,从最大值和最小值开始匹配再根据和目标值的比较移动,知道找到结果,时间复杂度为O(nlog(n)) 知识点:comparable 接口的使用,利用其进行对象的自然排序,相关文章 public class Solution { static class Node implements Compa