Alex Burrows Alex Burrows - 19 days ago 7
Java Question

Sorting an arrayList

I have to sort an arraylist by the date and time entered by the user but for some reason the output comes out not in order

Below this code it the code im using to order

public int compareTo(Vehicle v){
int returnValue = 0;
if (this.parkDate.year> v.parkDate.getYear() &&
this.parkDate.month> v.parkDate.getMonth() &&
this.parkDate.day> v.parkDate.getDay() &&
this.parkDate.hours> v.parkDate.getHours() &&
this.parkDate.minuets> v.parkDate.getMinuets()){
returnValue = 1; }
else
returnValue = - 1;
return returnValue;
}


Here is the output message

Answer

Your comparison logic isn't correct. You might perform your comparisons with Integer.compare(int, int) and return the result in the case of non-zero. Something like,

public int compareTo(Vehicle v) {       
    int returnValue = Integer.compare(this.parkDate.getYear(), 
            v.parkDate.getYear());
    if (returnValue != 0) {
        return returnValue;
    }
    returnValue = Integer.compare(this.parkDate.getMonth(), 
            v.parkDate.getMonth());
    if (returnValue != 0) {
        return returnValue;
    }
    returnValue = Integer.compare(this.parkDate.getDay(), 
            v.parkDate.getDay());
    if (returnValue != 0) {
        return returnValue;
    }
    returnValue = Integer.compare(this.parkDate.getHours(), 
            v.parkDate.getHours());
    if (returnValue != 0) {
        return returnValue;
    }
    return Integer.compare(this.parkDate.getMinuets(), 
            v.parkDate.getMinuets());
}

Or, you could shorten the above by using arrays and something like

int[] a = { this.parkDate.getYear(), this.parkDate.getMonth(), 
        this.parkDate.getDay(), this.parkDate.getHours(), 
        this.parkDate.getMinuets() };
int[] b = { v.parkDate.getYear(), v.parkDate.getMonth(), 
        v.parkDate.getDay(), v.parkDate.getHours(), 
        v.parkDate.getMinuets() };
for (int i = 0; i < a.length; i++) {
    int rv = Integer.compare(a[i], b[i]);
    if (rv != 0) {
        return rv;
    }
}
return 0;

Finally, I believe you want minutes not minuets.

Comments