0

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.

1
  • 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? Commented May 27, 2013 at 1:45

1 Answer 1

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;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.