在数组中以对象方式对对象进行排序

时间:2016-12-11 20:57:40

标签: java arrays sorting

import java.io.File;
import java.util.Scanner;

public class MainClass {

    public static Winner [] listOfWinners;

    public static void loadFromFile()
    {
        try{
            //Create instance of Scanner and provide instance of File pointing to the txt file
            Scanner input = new Scanner(new File("WorldSeriesWinners.txt"));

            //Get the number of teams
            int years = input.nextInt();
            input.nextLine();//move to the next line

            //Create the array
            listOfWinners = new Winner[years];

            //for every year in the text file
            for(int index = 0; index<years; index++)
            {
                //Get the year
                int year = input.nextInt();
                input.skip("    ");
                //Get the team
                String team = input.nextLine();

                //Create an instance of Winner and add it to the next spot in the array
                listOfWinners[index] = new Winner(team,year);
            }
        }catch(Exception e)
        {
            System.out.println("Something went wrong when loading the file!");
            System.out.println(e.toString());
            System.exit(0);
        }
    }

    public static void sortByTeamName()
    {

    }

我已经在线搜索了几个小时,但无法找到按字母顺序正确排序数组的方法

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码段按团队名称进行排序,方法是利用Arrays.sort(arr[],comparator)

的比较器功能
Arrays.sort(listOfWinners, new Comparator<Winner>() {

            @Override
            public int compare(Winner o1, Winner o2) {

                return o1.team.compareTo(o2.team);
            }
        });