6

我正在处理一个示例,它使用 ArrayList 包含新实例并使用可比较的接口使用 Collections.sort() 方法。我不知道为什么它会在排序时打印出哈希码以及我的代码中的错误在哪里。任何人都可以找出错误并详细解释我。

排序水果对象.java

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

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;
    }
}

输出:

[Fruit@36422510, Fruit@308f5944, Fruit@132d9844, Fruit@1667a232]
4

1 回答 1

10

您需要重写toString()方法来打印漂亮的输出,默认情况下它考虑 Object 的 toString() ,它的实现方式如下

   public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
   }

所以输出

于 2013-07-06T07:50:08.343 回答