La méthode hashcode()

Résolu
cs_limalima Messages postés 124 Date d'inscription dimanche 31 août 2008 Statut Membre Dernière intervention 16 décembre 2010 - 14 déc. 2008 à 16:15
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 - 24 déc. 2008 à 21:42
Bonjour à tous,
je suis en train d'étudier les collections, je n'arrive pas bien à comprendre la méthode hashcode(), si quelqu'un peut me donner quelques indications et informations sur cette méthode,merci.
A voir également:

3 réponses

uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
14 déc. 2008 à 19:25
"equals" et "hashCode" vont ensemble: deux objets sont logiquement égaux, si leurs méthodes "hashCode" retournent chacune la même valeur (si ont n'implémente pas "equals" et "hashCode", chaque objet est égal uniquement à lui-même). Voici un exemple très simple:

public class MyElement {
    private String name;
    private int id;
    public MyElement(String name, int id) {
        this.name = name;
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final MyElement other = (MyElement) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.id != other.id) {
            return false;
        }
        return true;
    }
    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 97 * hash + this.id;
        return hash;
    }
    @Override
    public String toString() {
        return "name: " + name + "  id: " + id;
    }
}

Le code suivant ne sortira qu'un seul élément:

Set set = new HashSet();
set.add(new MyElement("1", 1));   
set.add(new MyElement("1", 1));
System.out.println(set);

parce qu'un Set ne peut pas contenir des doublons.
Par contre, si on n'implémente pas "equals" et "hashCode", ce même code sortira deux éléments!
3