Search code examples
javaarraylistinterfacecompareto

Why is my output in byte-code and how do I get the string representation?


I've filled an array with instances of an object, sorted it using the compareTo method and I'm try to return the sorted list.

import java.util.Arrays;

public class test {


public static void main(String[] args) {
    Patients1 assetList = new Patients1[5];
    assetList = new Patients1[5];

    assetList[0] = new Patients1("VINTJAC001");
    assetList[1] = new Patients1("LEWGCOL002");
    assetList[2] = new Patients1("HENFBOR003");
    assetList[3] = new Patients1("ARTDMAN004");
    assetList[4] = new Patients1("KISCBIS005");

    Arrays.sort(assetList);
    System.out.println (Arrays.toString(assetList));
}
}

public class Patients1 implements Comparable<Patients1>{
private String patient_id;
public Patients1(String patient_id){
    this.patient_id=patient_id;
}
public String getPatient_id(){
    return patient_id;
}
@Override
public int compareTo(Patients1 p) {
    int result = 0;
    int compare = patient_id.compareTo(p.patient_id);
    if(compare < 0){
        result = -1;
    }
    else if (compare > 0){
        result = 1;
    }
    else if (compare == 0){
        result = 0;
    }
    return result;
}

}

However, this is the output I get:

[samples.Patients1@15db9742, samples.Patients1@6d06d69c, 
samples.Patients1@7852e922, samples.Patients1@4e25154f, 
samples.Patients1@70dea4e] /*samples is the package name 
and Patients1 is the class that has the compareTo method*/

It should be:

[ARTDMAN004, HENFBOR003, KISCBIS005, LEWGCOL002, VINTJAC001] (sorted list)

What am I doing wrong or just not doing?


Solution

  • You need to override the toString method in your Patients1 class.