I know there are a lot of questions like this, and I have been reading a lot but I really can't figure it out. I have a user defined object, Team, which has the properties team name (String), batAvg (Double) and slugAvg (Double). I want to arrange, and print the teams in order of descending batAvg, then in order of descending slugAvg. I have an array of all the teams, teamArray (Team[]). What is the best way to go about sorting this array by the teams batting and slugging average. I've tried a bunch of stuff, but none of it seems to work.
Asked
Active
Viewed 327 times
0
-
1*"I have been reading a lot but I really can't figure it out."* So what makes you think anything we write will suddenly help you to figure it out? – Andrew Thompson May 27 '13 at 01:45
1 Answers
0
Pls check the following code,
import java.util.Arrays;
import java.util.Comparator;
public class Team {
private String name;
private double batAvg;
private double slugAvg;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBatAvg() {
return batAvg;
}
public void setBatAvg(double batAvg) {
this.batAvg = batAvg;
}
public double getSlugAvg() {
return slugAvg;
}
public void setSlugAvg(double slugAvg) {
this.slugAvg = slugAvg;
}
public static void main(String[] argv){
Team[] teams = new Team[2]; //TODO, for testing..
Arrays.sort(teams, new TeamComparator()); //This line will sort the array teams
}
}
class TeamComparator implements Comparator<Team>{
@Override
public int compare(Team o1, Team o2) {
if (o1.getSlugAvg()==o2.getSlugAvg()){
return 0;
}
return o1.getSlugAvg()>o2.getSlugAvg()?-1:1;
}
}

Stony
- 3,541
- 3
- 17
- 23