为什么我会收到这个结果?JAVA
我正在学习使用比较器,在执行我的程序时,我在控制台中得到了一个非常奇怪的结果:
我定义了一个名为Zapato的对象,该对象的属性值在向用户请求参数后通过参数传递:
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;
}
}
然后我根据颜色或价格创建了一些比较器
public class OrdenarPorColor implements Comparator<Zapato>{
@Override
public int compare(Zapato z1, Zapato z2) {
return z1.color.compareTo(z2.color);
}
}
大体上,我要求输入值,创建3个对象,然后将它们保存在ArrayList上。然后,用户必须选择比较模式,我调用所选比较模式的类,在对列表进行排序后,我将其打印为已排序的3个对象:
//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;
但是当程序在系统中打印它们时。出来println(listaZapatos),它应该看起来像
45罗莎32,56蓝色21,34佛得角46
但我在控制台上收到了以下信息:
[Main。Zapato@2ff4acd0主要的Zapato@279f2327主要的Zapato@54bedef2]
当我每次在系统中请求使用引入值创建的对象时,它也会出现。出来println(“Zapato introxido es:+listaZapatos.get(2))所以我收到了这样的消息:
Main。Zapato@2ff4acd0
# 1 楼答案
您需要重写Zapato类中的
toString
实现。打印集合时,该方法将在内部对该集合中的每个对象调用toString()
。默认的toString
实现为您提供所需的数据像这样的东西会有帮助:
在你的
Zapato
课上