I want to sort a Coin array according to their values by using Selection sort but the output is not showing properly. The output display as some other unique format. I have tried to resolve the problem but still unable to find the solution. I have two classes CoinSelectionSorter and a Coin class. I am using Comparable interface to sort the Coin values. The entire code is like that-
CoinSelectionSorter.java:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
This class sorts an array of coins, using the selection sort
algorithm.
*/
public class CoinSelectionSorter {
public static void main (String args[])
{
//public void sort() {
Coin[] list = new Coin[] {new Coin(2, "Johan"),new Coin(5, "peter"), new Coin(1, "robin"),new Coin(15, "walker") }; // example data;
List <Coin> p = Arrays.asList(list);
Collections.sort(p);
System.out.println(p);
list = p.toArray(list);
System.out.println(p);
}
}
Coin.java:
public class Coin implements Comparable<Coin >{
Integer r;
String p;
public Coin(Integer r, String p) {
// TODO Auto-generated constructor stub
this.r = r;
this.p = p;
}
@Override
public int compareTo(Coin test) {
// TODO Auto-generated method stub
return this.r - test.r;
}
}
It gives output like:
[Coin@19821f, Coin@addbf1, Coin@42e816, Coin@9304b1]
[Coin@19821f, Coin@addbf1, Coin@42e816, Coin@9304b1]
But I expect output as:
[2, Johan], [5, 'peter], [1, robin], [15, walker]
[1, robin], [2, Johan], [5, 'peter], [15, walker]
Kindly help to resolve this issue. Thanks in advance.
All you need to is override the default toString() in coin to generate the output string in desired format. Like:
@Override
public String toString() {
return "[" + r + ", " + p + "]";
}
Additionally, to get the output you mentioned, you need to print the list of coins before sorting in CoinSelectionSorter.
You need to implement toString()
in your class Coin:
@Override
public String toString() {
return "Coin [r=" + r + ", p=" + p + "]";
}
This code has been generated with Eclipse. You can easily do that in Source > Generate toString()...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.