When using Collections.sort(), it sorts and prints the hashcode
本问题已经有最佳答案,请猛点这里访问。
我使用了一个示例,其中它使用arraylist包含新实例,并使用collections.sort()方法使用可比较的接口。我不知道它为什么会在分类时打印出哈希代码,以及我的代码中的错误在哪里。有人能找出错误并详细解释一下吗?
Sort水果对象.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.*; public class SortFruitObject{ public static void main(String[] args){ ArrayList<Fruit> frui = new ArrayList<Fruit>(); frui.add(new Fruit("Pine","PineDesc", 500)); frui.add(new Fruit("Apple","AppleDesc", 400)); frui.add(new Fruit("Banana","BananaDesc", 450)); frui.add(new Fruit("JackFruit","JackFruitDesc", 300)); Collections.sort(frui); System.out.println(frui); } } |
水果.java
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 | import java.io.*; import java.util.*; public class Fruit implements Comparable<Fruit>{ private String fruitName; private String fruitDesc; private int fruitQuantity; public int compareTo(Fruit f){ return fruitName.compareTo(f.getFruitName()); } public Fruit(String fruitName, String fruitDesc, int fruitQuantity){ this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.fruitQuantity = fruitQuantity; } public void setFruitName(String fruitName){ this.fruitName = fruitName; } public void setFruitDesc(String fruitDesc){ this.fruitDesc = fruitDesc; } public void setFruitQuantity(int fruitQuantity){ this.fruitQuantity = fruitQuantity; } public String getFruitName(){ return fruitName; } public String getFruitDesc(){ return fruitDesc; } public int getFruitQuantity(){ return fruitQuantity; } } |
号
输出:
1 | [Fruit@36422510, Fruit@308f5944, Fruit@132d9844, Fruit@1667a232] |
您需要重写
1 2 3 |
所以输出