简体   繁体   中英

Sorting an array using Array.sort() without a comparator

I have to sort an Array of custom objects by one of the object's params using Arrays.sort() , but WITHOUT passing a Comparator. This is a homework assignment and my professor wants us to do it without a comparator.

To be more specific I have an array[] of object type 'Female', female is made up of params 'name' and 'age'. I have to sort the array by age using Arrays.sort(femaleList) , but again I cannot use a Comparator.

I'm trying to use .getAge() or something like that, but it's not working. I'm assuming there's some relatively simple solution that I'm overlooking, any help would be greatly appreciated.

Unless I'm missing something, implement Comparable<Female> like

class Female implements Comparable<Female> {
    // ...
    public int compareTo(Female that) {
        if (this.age < that.age) {
            return -1;
        } else if (this.age > that.age) {
            return 1;
        }
        return 0;
    }
}

If you make the last line

return this.name.compareTo(that.name);

it will sort by name if any are the same age.

It can be as simple as this:

class Female implements Comparable<Female> {
    // ...
    public int compareTo(Female that) {
        return this.age - that.age;
    }
}

Because all you have to return is:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Be aware that this implementation comes with risks. This assumes that subtracting ages will not cause an overflow which could happen if their signs differ (essentially making this addition) and the sum of their magnitude was greater than age's type can hold.

Another important point to note is don't use subtraction for comparing integral values because result of subtraction can overflow as every int operation in Java is modulo 2^32. use either Integer.compareTo() or logical operators for comparison. There is one scenario where you can use subtraction to reduce clutter and improve performance. As we know compareTo doesn't care magnitude, it just care whether result is positive or negative. While comparing two integral fields you can use subtraction if you are absolutely sure that both operands are positive integer or more precisely [their difference] must be less than Integer.MAX_VALUE. In this case there will be no overflow and your compareTo will be concise and faster.

http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html

您需要使Female工具Comparable

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM