6

I was working with one example where it uses ArrayList contains new instances and using Collections.sort() method using the comparable interface. I dont know why it prints out the hashcode when it sorts and where the bug in my code. Can anyone please find out the mistake and explain me in detail.

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

Output:

[Fruit@36422510, Fruit@308f5944, Fruit@132d9844, Fruit@1667a232]
Java Beginer
  • 321
  • 2
  • 16

1 Answers1

10

You need to override toString() method to print pretty output, by default it considers Object's toString() which is implemented like

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

and so the output

jmj
  • 237,923
  • 42
  • 401
  • 438
  • +1 Thats Right. But your code didn't workout. Here is what i used now. `public String toString(){ return fruitName + " " + fruitDesc + " " + fruitQuantity + "\n"; }` – Java Beginer Jul 06 '13 at 07:54
  • 5
    @JavaBeginer. He has given how the default `toString` looks like, not how you should do. This is what you need to override, which you have done now. – Rohit Jain Jul 06 '13 at 07:56