Essej
Essej

Reputation: 861

Java Use compareTo to Compare Two Objects

I am to write a method which will implement the compareTo method to compare the objects in my array to decide which is the biggest. Here is my code:

public static Object max(Object[] array) {
    for (int i = 0; i < array.length; i++) {
        Object lol = (array[0].compareTo(array[i]));     
    }
    return; // what should be returned?
}

Could anyone explain to me how to actually use compareTo, and what it should return?

Upvotes: 1

Views: 3764

Answers (1)

Lencalot
Lencalot

Reputation: 395

You are going to need something like this.

Object biggestObject = array[0];
    for (Object obj: array){
        if (biggestObject.compareTo(obj) == 1){
            biggestObject = obj;
        }
    }
 return biggestObject;

If you are using a custom object you are going to need to override the compareTo method so like if the object is a person and we are comparing Pen... feet size, then we would want to set up compareTo to compare feet sizes, returning 1 when the object being compared to is bigger, 0 if its the same, and -1 if its smaller.

@Override
public int compareTo(Object obj){
    if (this.feetSize < obj.getFeetSize()){
        return 1;
    etc, etc....

Upvotes: 1

Related Questions