最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解java中保持compareTo和equals同步

 更新時(shí)間:2017年03月15日 10:11:03   投稿:lqh  
這篇文章主要介紹了詳解java中保持compareTo和equals同步的相關(guān)資料,需要的朋友可以參考下

詳解java中保持compareTo和equals同步

摘要 : 介紹重寫equlas()和comparable接口,兩者進(jìn)行不相同的判斷。從而使兩者的對(duì)應(yīng)的list.indexOf()與 Collections.binarySearch()得到的不一樣。

在Java中我們常使用Comparable接口來(lái)實(shí)現(xiàn)排序,其中compareTo是實(shí)現(xiàn)該接口方法。我們知道compareTo返回0表示兩個(gè)對(duì)象相等,返回正數(shù)表示大于,返回負(fù)數(shù)表示小于。同時(shí)我們也知道equals也可以判斷兩個(gè)對(duì)象是否相等,那么他們兩者之間是否存在關(guān)聯(lián)關(guān)系呢?

public class Student implements Comparable<Student>{
  private String id;
  private String name;
  private int age;

  public Student(String id,String name,int age){
    this.id = id;
    this.name = name;
    this.age = age;
  }

  public boolean equals(Object obj){
    if(obj == null){
      return false;
    }

    if(this == obj){
      return true;
    }

    if(obj.getClass() != this.getClass()){
      return false;
    }

    Student student = (Student)obj;
    if(!student.getName().equals(getName())){
      return false;
    }

    return true;
  }

  public int compareTo(Student student) {
    return this.age - student.age;
  }

  /** 省略getter、setter方法 */
}

Student類實(shí)現(xiàn)Comparable接口和實(shí)現(xiàn)equals方法,其中compareTo是根據(jù)age來(lái)比對(duì)的,equals是根據(jù)name來(lái)比對(duì)的。

public static void main(String[] args){
    List<Student> list = new ArrayList<>();
    list.add(new Student("1", "chenssy1", 24));
    list.add(new Student("2", "chenssy1", 26));

    Collections.sort(list);  //排序

    Student student = new Student("2", "chenssy1", 26);

    //檢索student在list中的位置
    int index1 = list.indexOf(student);
    int index2 = Collections.binarySearch(list, student);

    System.out.println("index1 = " + index1);
    System.out.println("index2 = " + index2);
  }

按照常規(guī)思路來(lái)說應(yīng)該兩者index是一致的,因?yàn)樗麄儥z索的是同一個(gè)對(duì)象,但是非常遺憾,其運(yùn)行結(jié)果:

index1 = 0

index2 = 1

為什么會(huì)產(chǎn)生這樣不同的結(jié)果呢?

這是因?yàn)閕ndexOf和binarySearch的實(shí)現(xiàn)機(jī)制不同。

indexOf是基于equals來(lái)實(shí)現(xiàn)的只要equals返回TRUE就認(rèn)為已經(jīng)找到了相同的元素。

而binarySearch是基于compareTo方法的,當(dāng)compareTo返回0 時(shí)就認(rèn)為已經(jīng)找到了該元素。

在我們實(shí)現(xiàn)的Student類中我們覆寫了compareTo和equals方法,但是我們的compareTo、equals的比較依據(jù)不同,一個(gè)是基于age、一個(gè)是基于name。比較依據(jù)不同那么得到的結(jié)果很有可能會(huì)不同。

所以知道了原因,我們就好修改了:將兩者之間的比較依據(jù)保持一致即可。

對(duì)于compareTo和equals兩個(gè)方法我們可以總結(jié)為:compareTo是判斷元素在排序中的位置是否相等,equals是判斷元素是否相等,既然一個(gè)決定排序位置,一個(gè)決定相等,所以我們非常有必要確保當(dāng)排序位置相同時(shí),其equals也應(yīng)該相等。

細(xì)節(jié) : 實(shí)現(xiàn)了compareTo方法,就有必要實(shí)現(xiàn)equals方法,同時(shí)還需要確保兩個(gè)方法同步

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

九龙城区| 囊谦县| 分宜县| 城市| 乌鲁木齐市| 台湾省| 孝感市| 南京市| 饶河县| 阳江市| 互助| 富顺县| 呼伦贝尔市| 巨野县| 濮阳市| 都匀市| 岳阳县| 滨海县| 尼勒克县| 广西| 嘉义市| 集贤县| 沙河市| 柞水县| 彰武县| 孝昌县| 莱芜市| 名山县| 拉萨市| 肥东县| 庐江县| 赣榆县| 三明市| 鹤岗市| 剑川县| 洛川县| 崇州市| 漳浦县| 桐乡市| 尼玛县| 漾濞|