2012-09-04 14 views
5

मैं दो सेट है:जावा assertEquals सेट

Set<Attribute> set1 = new HashSet<Attribute>(5); 
Set<Attribute> set2 = new HashSet<Attribute>(5); 

//add 5 attribute objects to each of them. (not necessarily the same objects) 


assertEquals(set1,set2); //<--- returns false, even though 
         //the added attribute objects are equal 

बराबर गुण की विधि ओवरराइड की गई है, मेरे आवश्यकताओं के अनुसार:

public abstract class Attribute implements Serializable{ 

public int attribute; 

public abstract boolean isNumerical(); 

@Override 
public boolean equals(Object other){ 
    if(!(other instanceof Attribute)){ 
     return false; 
    } 

    Attribute otherAttribute = (Attribute)other; 
    return (this.attribute == otherAttribute.attribute && 
      this.isNumerical() == otherAttribute.isNumerical()); 
} 

} 

जब डीबगिंग, बराबरी विधि भी कहा जाता है नहीं है!

कोई विचार?

+1

की बराबरी से इस्तेमाल किया यह भी देखें है: [अधिभावी के बराबर होती है और जावा में hashCode] (http://stackoverflow.com/questions/27581) – McDowell

+0

@McDowell: धन्यवाद! मुझे पता था कि यदि हैशकोड 2 ऑब्जेक्ट्स के लिए अलग-अलग मान देता है तो बराबर कॉल से सच होने का कोई मौका नहीं है। मैं जल्दी में था! :) – Razvan

उत्तर

13

आप hashCode() ओवरराइड नहीं कर रहे हैं, जिसका अर्थ है कि डिफ़ॉल्ट कार्यान्वयन का उपयोग किया जाएगा। HashSet हैश कोड पहले से मिलान करने के लिए चेक करता है, equals पर कॉल करने से पहले - इस तरह संभावित मैचों को इतनी कुशलता से ढूंढने का प्रबंधन होता है। (यह एक पूर्णांक "बाल्टी" आसान है।)

असल में, आपको hashCode को इस तरीके से ओवरराइड करने की आवश्यकता है जो आपके equals विधि के अनुरूप है।

+0

जिसका अर्थ है कि यदि 'बराबर' सत्य लौटाता है, तो हैशकोड को भी सच करना होगा (केवल इस दिशा में)। – brimborium

0

यदि आप HashSet विधि स्रोत कोड containsKey() पर कॉल करते हैं जो getEntry() पर कॉल करता है। नीचे दिए गए स्रोत कोड के अनुसार यह स्पष्ट है कि बराबर कॉल करने के लिए उचित hashcode() कार्यान्वयन की आवश्यकता है।

/** 
* Returns the entry associated with the specified key in the 
* HashMap. Returns null if the HashMap contains no mapping 
* for the key. 
*/ 
final Entry<K,V> getEntry(Object key) { 
    int hash = (key == null) ? 0 : hash(key.hashCode()); 
    for (Entry<K,V> e = table[indexFor(hash, table.length)]; 
     e != null; 
     e = e.next) { 
     Object k; 
     if (e.hash == hash && 
      ((k = e.key) == key || (key != null && key.equals(k)))) 
      return e; 
    } 
    return null; 
} 

पुनश्च: Contains() विधि AbstractCollection