1
C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más / Java ordenar ArrayList no funciona solución método compareTo criterio ordenación
« en: 20 de Enero 2021, 04:38 »
Hola, mi problema viene al intentar ordenar un ArrayList de jugadores por sus ids, el problema viene que al ser el id con números me pilla solo el primero,al ser letras lo ordena bien al ser String. Hay alguna solución para que pueda hacer ambas formas? Se pase letras o números, siendo id un String.Gracias! Paso algunos ejemplos:
Sale por pantalla:
ID: j1 Nombre: maria
ID: j10 Nombre: maria
ID: j20 Nombre: juan
ID: j3 Nombre: pepe
ID: jA Nombre: pepe
ID: jB Nombre: maria
ID: jC Nombre: maria
ID: jD Nombre: juan
Collections.sort llama a:
Código: [Seleccionar]
ArrayList <Jugador> jugadores = new ArrayList<Jugador>();
jugadores.add(new Jugador("j3","pepe"));
jugadores.add(new Jugador("j20","juan"));
jugadores.add(new Jugador("j1","maria"));
jugadores.add(new Jugador("j10","maria"));
Collections.sort(jugadores);
for(Jugador jug: jugadores) jug.mostrarDatos();
Sale por pantalla:
ID: j1 Nombre: maria
ID: j10 Nombre: maria
ID: j20 Nombre: juan
ID: j3 Nombre: pepe
Código: [Seleccionar]
ArrayList <Jugador> jugadores = new ArrayList<Jugador>();
jugadores.add(new Jugador("jA","pepe"));
jugadores.add(new Jugador("jD","juan"));
jugadores.add(new Jugador("jC","maria"));
jugadores.add(new Jugador("jB","maria"));
Collections.sort(jugadores);
for(Jugador jug: jugadores) jug.mostrarDatos();
ID: jA Nombre: pepe
ID: jB Nombre: maria
ID: jC Nombre: maria
ID: jD Nombre: juan
Collections.sort llama a:
Código: [Seleccionar]
public int compareTo(Jugador j) { //Ordena por ID
// TODO Auto-generated method stub
return this.id.compareTo(j.id);
}