2012-09-04 7 views
5

Tengo dos conjuntos:assertEquals java establece

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 

los iguales se anula método de atributo, de acuerdo a mis necesidades:

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()); 
} 

} 

cuando la depuración, el método es igual ni siquiera se llama!

¿Alguna idea?

+1

Ver también: [Anulación es igual y hashCode en Java] (http://stackoverflow.com/questions/27581) – McDowell

+0

@McDowell: gracias! Sabía que si hashCode devuelve diferentes valores para 2 objetos, entonces no hay posibilidad de obtener una verdadera de la llamada igual. ¡Estaba en un apuro! :) – Razvan

Respuesta

13

No invalidará hashCode(), lo que significa que se usará la implementación predeterminada. HashSet comprueba la coincidencia de los códigos hash primero, antes de llamar al equals - así es como logra encontrar posibles coincidencias de manera tan eficiente. (Es fácil "agrupar" un número entero.)

Básicamente, debe anular hashCode de una manera que sea coherente con su método equals.

+0

Lo que significa que si 'equals' devuelve verdadero,' hashCode' tiene que devolver true también (solo en esta dirección). – brimborium

0

Si comprueba el código fuente de HashSet llamadas al método containsKey() que llama a getEntry(). De acuerdo con el siguiente código fuente, está claro que se necesita una implementación adecuada de hashcode() para llamar a iguales.

/** 
* 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; 
} 

PS: Contains() método se utiliza de igual a igual de AbstractCollection

Cuestiones relacionadas