Dimebag Dimebag - 4 months ago 9
Java Question

Sorting an object array based on a property

EDIT: Added some information.

I got an array of Objects. Each object has a name and a value. I need to sort the objects in descending order of those values, and print the names. I saw this easy solution but can't seem to apply it to my problem: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

The code compiles with no error but the array is not sorted at all. I know this because I know what the output should be i.e. the output should be something like var364, var200, var65 etc. and what i get is var1, var2, var3 etc.

I tried to strip the code of the irrelevant parts here:

Main class

print(data.preselection());

private void print (UnitRow preselectedUnitRow) {
out.printf("Variables after preselection: \n");
for (int i=0;i<PRESELECTION_LIMIT;i++) {
out.printf("%s, ",preselectedUnitRow.getUnitName(i));
}
}


Dataset (data)

private UnitRow data;

...

public UnitRow preselection() {
UnitRow standardDeviationUnits = new UnitRow(numberOfVariables);
for (int i=0;i<numberOfVariables;i++){
Unit unit = new Unit(1,variableNames[i],calculateStandardDeviation(i));
standardDeviationUnits.add(unit);
}
standardDeviationUnits.sort();
return standardDeviationUnits;
}


UnitRow

import java.util.Arrays;

public class UnitRow {

private Unit[] units;
private int count;

...

public void sort() {
Arrays.sort(units);
}
}


Unit

public class Unit implements Comparable<Unit>{

private NumberRow elements; //just a class with an array of doubles
private String name;

...

@Override
public int compareTo(Unit compareUnit) { //getValue returns a single type double number
int comparison = (int) (compareUnit.getValue(0) - getValue(0));
return comparison;
}
}


I am assuming my implementation of Comparable is wrong. Can you spot the problem?
I say this because I tested as following:

System.out.println(standardDeviationUnits.getValue(0,0));
standardDeviationUnits.sort();
System.out.println(standardDeviationUnits.getValue(0,0));


And the exact same value is returned.

Answer

It looks like reverse order

public int compareTo(Unit compareUnit) {
    if (getValue(0) < compareUnit.getValue(0)) return 1;
    else if (getValue(0) > compareUnit.getValue(0)) return -1;
    return 0;
}

Try this.

Also note that in your compareTo, you unnecessarily wrote return 2; and wrote 3 if instead of 1 if-else.