Java Reference
In-Depth Information
return getFirstName() + " " + getLastName() + "
- " + getPosition();
}
// ** getters and setters removed for brevity **
/**
* Returns a positive integer if Player A has more
goals than Player B
* Returns a negative integer if Player A has fewer
goals than Player B
* Returns a zero if both Player A and Player B have
the same number of goals
* @param a
* @param b
* @return
*/
public static int compareByGoal(Player a, Player b){
int eval;
if(a.getGoals() > b.getGoals()){
eval = 1;
} else if (a.getGoals() < b.getGoals()){
eval = -1;
} else {
eval = 0;
}
return eval;
}
}
The Player.compareByGoal() method could be used to sort an array of
Player objects. To do so, pass an array of Player objects ( Player[] ) to the Ar-
rays.sort() method as the first argument, and pass a method reference Play-
er::compareByGoal as the second argument. The result will be a sorted list (in as-
cending order) of Player objects by number of goals. The following line of code
shows how to accomplish this task.
Search WWH ::




Custom Search