I am learning to use Comparators and I am getting a very strange result in the console when executing my program:
I define an Object called Zapato whose attribute's values are passed through the arguments after asked for them to the user:
public class Zapato {
int talla;
String color;
int precio;
public Zapato (int talla,String color,int precio){
this.talla = talla;
this.color = color;
this.precio = precio;
}
}
Then I created some comparators based on the color or the price for example.
public class OrdenarPorColor implements Comparator<Zapato>{
@Override
public int compare(Zapato z1, Zapato z2) {
return z1.color.compareTo(z2.color);
}
}
In Main I ask for the values,create 3 objects and I save them on an ArrayList.Then the user has to select the comparison mode and I invoke the class of the comparison mode selected and after sorting the list,I print it the 3 objects sorted:
//Before this there is code repeated where I ask the values for the other 2 objects
System.out.println("Introduzca la talla,el color y la talla de los zapatos: ");
System.out.println("Talla: ");
talla = Integer.parseInt(sc.nextLine());
System.out.println("Color: ");
color = sc.nextLine();
System.out.println("Precio: ");
precio = Integer.parseInt(sc.nextLine());
listaZapatos.add(new Zapato(talla,color,precio));
System.out.println("Zapato introducido es: " + listaZapatos.get(2));
System.out.println("Escriba la opcion para comparar:");
System.out.println("1-Por talla\n2-Por color\3-Por precio");
System.out.println("Opcion: ");
int opcion = sc.nextInt();
switch (opcion){
case 1:
Collections.sort(listaZapatos,new OrdenarPorTalla());
System.out.println(listaZapatos);
break;
case 2:
Collections.sort(listaZapatos,new OrdenarPorColor());
System.out.println(listaZapatos);
break;
case 3:
Collections.sort(listaZapatos,new OrdenarPorPrecio());
System.out.println(listaZapatos);
break;
}
return;
But when the program prints them System.out.println(listaZapatos) ,it should appear something like
45 Rosa 32,56 Azul 21,34 Verde 46
but instead I receive this on the console:
[Main.Zapato@2ff4acd0, Main.Zapato@279f2327, Main.Zapato@54bedef2]
Also it appears when I print the object created with the introduced values every time I ask for them in System.out.println("Zapato introducido es: " + listaZapatos.get(2)) so I receive things like this:
Main.Zapato@2ff4acd0