使用Collections.sort()时,它会对哈希码进行排序和打印

时间:2013-07-06 07:48:39

标签: java sorting interface comparable

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

SortFruitObject.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);
    }
}

Fruit.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]

1 个答案:

答案 0 :(得分:10)

你需要覆盖toString()方法来打印漂亮的输出,默认情况下它会考虑Object的toString(),它实现为

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

等输出