Méthode compareTo dans un tableau

Fermé
shadow25 - 8 janv. 2017 à 18:53
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 - 8 janv. 2017 à 20:35
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.


1 réponse

KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
8 janv. 2017 à 20:35
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