Méthode compareTo dans un tableau

shadow25 -  
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   -
Bonjour,

J'aimerai retirer un élément d'un tableau (ici de type String). Sauf que j'ai l'impression que ma méthode ne fonctionne pas correctement...

	public boolean supprimerUnParticipant(String participant) {
		for (int i = 0 ; i < nombreInscrits; i++){
			if (tableParticipants[i].compareTo(participant) < 0){
				this.tableParticipants[i] = tableParticipants[nombreInscrits - 1];
				nombreInscrits--;
				this.tableParticipants[nombreInscrits] = null;
			}
		}return false;
	}


Seriez-vous me dire si j'utilise bien la méthode compareTo()?
Merci.


A voir également:

1 réponse

KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Bonjour,

a.compareTo(b) renvoie <0 si a<b. Or si tu veux supprimer quand a=b, il faudrait plutôt faire a.compareTo(b)=0, c'est à dire a.equals(b) en général.

public boolean supprimerUnParticipant(String participant) {
    for (int i = 0; i < nombreInscrits; i++) {
        if (tableParticipants[i].equals(participant)) {
	    nombreInscrits--;
            tableParticipants[i] = tableParticipants[nombreInscrits];
            tableParticipants[nombreInscrits] = null;
            return true;
        }
    }
    return false;
}
0