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]
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface.
Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects.
If you just want to sort a list, use any kind of List and use Collections. sort(). If you want to make sure elements in the list are unique and always sorted, use a SortedSet.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With