Bonsoir,
Voila, je veux trier une liste d'objets Personne , j'ai donc chercher sur le net
et je n'arrive pas à avoir ma liste triés.
Voic mon code :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public static void main(String[] args) {
	liste1.add(new Personne (1,"dupont","jean"));
	liste1.add(new Personne (5,"martin","joseph"));
	liste1.add(new Personne (4,"martinet","alain"));
	liste1.add(new Personne (3,"andre","gilles"));
	liste1.add(new Personne (5,"Zachari","philippe"));
 
	Collections.sort(liste1);
	for (Iterator iter = liste1.iterator(); iter.hasNext();) {
	    Personne p   = (Personne) iter.next();
	    System.out.println("id = " + p.getId() + " nom = " + p.getNom() + " prenom = " + p.getPrenom());
	} 
 
} 
...............
public class Personne  implements Comparable {
private long id=0;
private String nom=null;
private String prenom=null;
 
 
public Personne(long id, String nom, String prenom) {
	super();
	this.id = id;
	this.nom = nom;
	this.prenom = prenom;
}
/**
 * @return the id
 */
public long getId() {
	return id;
}
/**
 * @param id the id to set
 */
public void setId(long id) {
	this.id = id;
}
/**
 * @return the nom
 */
public String getNom() {
	return nom;
}
/**
 * @param nom the nom to set
 */
public void setNom(String nom) {
	this.nom = nom;
}
/**
 * @return the prenom
 */
public String getPrenom() {
	return prenom;
}
/**
 * @param prenom the prenom to set
 */
public void setPrenom(String prenom) {
	this.prenom = prenom;
}
/**
 * CompareTo : Permet de trier par nom prénom 
 */
public int compareTo(Object o) // on redéfinit compareTo(Object)
{
  Personne p=(Personne)o;
  if(nom.equals(p.nom))
  {    
    return prenom.compareTo(p.prenom);
  }
 return nom.compareTo(p.nom);
}
 
}
Et ça donne cela :
id = 5 nom = Zachari prenom = philippe
id = 3 nom = andre prenom = gilles
id = 1 nom = dupont prenom = jean
id = 5 nom = martin prenom = joseph
id = 4 nom = martinet prenom = alain


Pourtant je l'ai au boulot sur des objets plus complexes et ça fonctionne !!


D'abord quelqu'un peut-il me dépanner et ensuite me dire comment on fait pour avoir un second critère de tri pour cette liste (par exemple tri sur prénom, nom)
Merci bcp