hashTable problème equals
Bonjour,
D'après ce que j'avais compris lorsque la méthode hashCode créer un code identique pour 2 valeurs, c'est la méthode equals qui ajuste la bonne valeur,
Dans mon test (avec un hashcode volontairement absurde) pour 1clé ayant 2 valeurs je n'ai qu'une valeur qui s'affiche.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package applihashtable;
import java.util.*;
public class Roman {
/** Creates a new instance of Roman */
private String nomO;
private int noIsbO;
public Roman(String n, int i) {
this.nomO = n;
this.noIsbO = i;
}
public void setNomTitre(String n){
this.nomO = n;
}
public void setNoIsbn(int i){
this.noIsbO = i;
}
public String getNomTitre(){
return(this.nomO);
}
//
public int hashCode(){
return (this.nomO.length());
//Je considère le nb de char du titre comme hashcode (volontairement
//absurde
}
public boolean equals(Object obj){
return (this.noIsbO == ((Roman)obj).noIsbO);
//Pour des clé identique on teste le numéro ISBN de l'instance en cours
//que l'on compare au cast de l'objet transmis'
//Note si les 2 romans ont le même ISBN equal n'en ressort qu'1 !!!'
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public static void main(String[] args) {
Hashtable maTable;
maTable = new Hashtable();
Roman livre = new Roman("A l'Ouest", 1);
maTable.put(livre.hashCode(), livre);
livre = new Roman("A l'Est..", 2);
maTable.put(livre.hashCode(), livre);
//A l'ouest ET A L'Est... font avoir la même clé : 9'
for (Enumeration e = maTable.keys(); e.hasMoreElements();){
livre = (Roman)maTable.get(e.nextElement());
System.out.println(livre.getNomTitre());
} |
le println ne me renvoi que A l'Est..
Merci de votre aide