Using Comparable

空扰寡人 提交于 2019-12-20 06:56:05

问题


Looking for assistance for following issue running into have following comparable method below that want to print largest value of goals scored from my Hockey Player ArrayList. I'm unable to store values from the for each loop successfully to pass it to the comparable method. Any suggestion what I'm doing wrong?

public static Comparable maximum(Comparable first, Comparable second, Comparable third) {
    if (first.compareTo(second) > 0) {
        if (first.compareTo(third) > 0) {
            return first;
        }
        return third;
    } else if (second.compareTo(third) > 0) {
        return second;
    }
    return third;
}

for (HockeyPlayer hp : hockeyPlayerList){
    int first = ((HockeyPlayer) hp).getGoalsScored(); {
        first = player1;
        first = player2;
        first = player3;
        first = player4;
    }
    System.out.println("The largest string is: " + Driver.maximum(player1,player2,player3));
}

回答1:


I generally agree with "use java.util.Collections.sort(hockeyPlayerList);" comment, but just if you have to implement your own maximum...

Assuming your final goal is to be able to do this:

System.out.println("The largest string is: " + Driver.maximum(player1,player2,player3));

The function could looks like this:

public class Driver {

...

    public static Comparable maximum(Comparable... items) 
    {
        if(items.length ==  0)
        {
            return null; // no items to compare
        }

        Comparable currentMax = items[0];

        for(Comparable item : items)
        {
            // Update currentMax only if next element is larger
            currentMax = currentMax.compareTo(item) > 0 ? currentMax : item;
        }

        return currentMax;
    }
}

And inside your Player class you will have to have a toString function printing out a meaningful info about the player (System.out.println will call toString function for an instance of the Player class returned by a maximum function). Something like (I am giving and example, use actual fields you have in Player function):

public class Player {

    ...
    @Override
    public String toString()
    { 
        return this.getPlayerName() + ": " + this.getGoalsScored();
    }
}

Also the following fragment of the code makes no sense:

int first = ((HockeyPlayer) hp).getGoalsScored(); {
    first = player1;
    first = player2;
    first = player3;
    first = player4;
}

not sure what you were trying to accomplish there



来源:https://stackoverflow.com/questions/35978462/using-comparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!