簡體   English   中英

比較類的兩個列表而不迭代列表

[英]Comparing two Lists of a class without iterating the lists

我有一個Abc如下課程

public class Abc {
  int[] attributes;

  Abc(int[] attributes){
    this.attributes = attributes;
  }
}

如下覆蓋Abc哈希碼

@Override
public int hashCode() {
    int hashCode = 0;
    int multiplier = 1;
    for(int i = attributes.length-1 ; i >= 0 ; i++){
        hashCode = hashCode+(attributes[i]*multiplier);
        multiplier = multiplier*10;
    }       
    return hashCode;    
}

我正在使用上面的類來創建對象列表,並且我想比較兩個列表是否相等,即具有相同屬性的對象的列表。

    List<Abc> list1 ;
     list1.add(new Abc(new int[]{1,2,4}));
     list1.add(new Abc(new int[]{5,8,9}));
     list1.add(new Abc(new int[]{3,4,2}));
   List<Abc> list2;       
     list2.add(new Abc(new int[]{5,8,9}));
     list2.add(new Abc(new int[]{3,4,2}));
      list2.add(new Abc(new int[]{1,2,4}));

如何比較上面的兩個列表,以及是否對每個列表進行迭代。 還有什么更好的方法可以覆蓋哈希碼,以使具有相同屬性(值和順序)的兩個類相等。

您必須重寫類Abc equals函數。 如果使用的是IDE,則可以用來生成足夠好的東西。 例如,Eclipse產生以下內容:

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    Abc other = (Abc) obj;
    if (!Arrays.equals(attributes, other.attributes)) {
        return false;
    }
    return true;
}

使用此equals方法,您現在可以檢查Abc兩個實例是否相等。

如果要比較兩個列表list1list2 ,不幸的是您不能簡單地做

boolean listsAreEqual = list1.equals(list2); // will be false

因為這不僅會檢查列表中的元素是否相同,而且還會檢查它們的順序是否相同。 您可以做的是比較兩個集合,因為在集合中,元素沒有順序。

boolean setAreEqual = new HashSet<Abc>(list1).equals(new HashSet<Abc>(list2)); // will be true.

請注意,在這種情況下,您應將hashcode()實現保留在Abc ,以使HashSet正常運行。 通常,實現equals的類也應實現hashcode

SetHashSetSet )的問題是,從設計HashSet ,它將不包含幾個彼此相等的對象。 保證對象在集合中是唯一的。 例如,如果在第二組中添加新的new Abc(new int[]{5,8,9}) ,則這兩個組將仍然相等。

如果您不滿意,那么可能的解決方案是比較兩個列表,但先對它們進行排序(為此,您必須提供一個比較器或實現compareTo ),或者使用Guava的HashMultiset ,這是一個可以包含相同列表的無序容器對象多次。

覆蓋equals方法以比較對象。 如評論所述,在覆蓋equals方法時,您也應該覆蓋hashcode方法。

這樣

因此具有相同屬性(值和順序)的兩個類應相等。

我認為您的意思是兩個具有相同屬性的對象。

你可以嘗試這樣的事情

public boolean equals(Object o) {
  if(!(Object instanceOf Abc)) {
    return false;
  }
  Abc instance = (Abc)o;
  int[] array = instance.attributes;
  for(i=0;i<array.length;i++){
      if(array[i]!=this.attributes[i]) {
        return false;
      }
  }
}

編輯:至於hashcode的概念是

object1.equals(object2)

是真的,那么

object1.hashcode()

object2.hashcode() 

必須返回相同的值。 對象的hashCode()hashCode()在整個生命周期中應相同且一致。 因此,根據其實例變量的值生成哈希碼不是一個好選擇,因為當實例變量值更改時,可能會生成不同的哈希碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM