java – 使用Collections.sort()时,它会对hashcode 进行排序和打印

前端之家收集整理的这篇文章主要介绍了java – 使用Collections.sort()时,它会对hashcode 进行排序和打印前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How do I print my Java object without getting “SomeType@2f92e0f4”?10个
我正在使用一个示例,它使用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]

解决方法

你需要覆盖toString()方法来打印漂亮的输出,默认情况下它会考虑Object的toString(),它被实现为
public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
   }

输出

原文链接:https://www.f2er.com/java/121973.html

猜你在找的Java相关文章