加速/提高Java数组类的性能

时间:2017-11-07 02:14:22

标签: java arrays performance

对于课程,我必须使用数组编写一个程序,其中有人可以在特定时间范围内查找流行的婴儿名字。 (例如:1890年至1910年间最受欢迎的男孩和女孩名字是....)

我认为该计划很不错,但运行速度很慢。我不知道这只是因为我的代码,还是一个简单的程序查看大文件;但有没有办法加快这个过程?

import java.io.*;
import java.util.*;
import java.net.URL;

public class BabyNamesMainDriver {

// ===========================================================================================

private static void process(Scanner sc, String[] args) throws Exception {
    // The two arrays
    ArrayList<BabyNameClass> boys = new ArrayList<BabyNameClass>();
    ArrayList<BabyNameClass> girls = new ArrayList<BabyNameClass>();

    System.out.println("Enter a start year between 1880 and 2016:");// start year
    int startYear = sc.nextInt();
    if (startYear < 1880 || startYear > 2016)// Error check
        System.out.println("ERROR: Invalid start year.\n");
    else
        System.out.println("Enter a end year. Must be less then 2016 but greater than the start year :");// End year
    int endYear = sc.nextInt();
    if (endYear < 1880 || endYear > 2016)// Error check
        System.out.println("ERROR: Invalid end year. \n");
    else
        System.out.println("Enter the number of baby names to list. ");// Number of baby names
    int numOfNames = sc.nextInt();
    // if (topBabies <= 0);//Error Check
    // System.out.println("ERROR: Invalid number of names. \n");

    ReadBabyNames(startYear, endYear, boys, girls);// Reads file info

    // Header for top girl names
    System.out.print("\nTop " + numOfNames + " Girl names:\n");
    for (int i = 0; i < numOfNames; i++) {
        System.out.println(girls.get(i));
    }
    // Header for top boy names
    System.out.print("\nTop " + numOfNames + " Boy names:\n");
    for (int i = 0; i < numOfNames; i++) {
        System.out.println(boys.get(i));
    }
    sc.nextLine();
}

// ===========================================================================================

private static void ReadBabyNames(int startYear, int endYear, ArrayList<BabyNameClass> boys,
        ArrayList<BabyNameClass> girls) throws IOException, Exception {
    System.out.println("Please stand by...");

    for (int year = startYear; year <= endYear; year++) {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(
                new URL("https://cs.stcc.edu/~silvestri/babynames/yob" + year + ".txt").openStream());// file from
                                                                                                        // URL

        sc.useDelimiter("\\s*,\\s*|\\s+");

        while (sc.hasNextLine()) {
            String name = sc.next();
            String sex = sc.next();
            int number = sc.nextInt();
            sc.nextLine();
            BabyNameClass babies = new BabyNameClass(name, number);
            Collections.sort(boys);
            Collections.sort(girls);
            // Getting number of lil' babies
            if (sex.equalsIgnoreCase("F")) {
                int index = 1;
                index = girls.indexOf(babies);
                if (index == -1)
                    girls.add(babies);
                else
                    girls.get(index).addToAmount(number);
            } else {
                int index = 1;
                index = boys.indexOf(babies);
                if (index == -1)
                    boys.add(babies);
                else
                    boys.get(index).addToAmount(number);
            }
        }
    }
}
// ===========================================================================================

public static void main(String args[]) throws Exception {
    final String TITLE = "Baby Name Ranking";
    final String CONTINUE_PROMPT = "\nDo this again? [y/N] ";

    System.out.println("Welcome to " + TITLE);
    Scanner sc = new Scanner(System.in);
    do {
        process(sc, args);
    } while (doThisAgain(sc, CONTINUE_PROMPT));
    sc.close();
    System.out.println("Thank you for using " + TITLE);
}
// ===========================================================================================

private static boolean doThisAgain(Scanner sc, String prompt) {
    System.out.print(prompt);
    String doOver = sc.nextLine();
    return doOver.equalsIgnoreCase("Y");
}

}

第二课

public class BabyNameClass implements Comparable<BabyNameClass> {

// ==========================
private String name;
private int num;

// ===========================================================================================
public BabyNameClass(String name, int num) {
    this.name = name;
    this.num = num;
}

// ===========================================================================================
public String getName() {
    return this.name;
}

// ===========================================================================================
public int getNum() {
    return this.num;
}

// ===========================================================================================
public void addToAmount(int num) {
    this.num += num;
}

// ===========================================================================================
public void setAmount(int num) {
    this.num = num;
}

// ===========================================================================================

public boolean equals(Object lak) {
    if (lak == null)
        return false;
    if (this == lak)
        return true;
    if (getClass() != lak.getClass())
        return false;
    BabyNameClass Gu = (BabyNameClass) lak;
    if (name == null) {
        if (Gu.name != null)
            return false;
    } else if (!name.equals(Gu.name))
        return false;
    return true;
}

// ===========================================================================================
public int compareTo(BabyNameClass arg0) {
    if (this.num < arg0.num)
        return 1;
    if (this.num > arg0.num)
        return -1;
    if (this.name.compareTo(arg0.name) > 0)
        return 1;
    if (this.name.compareTo(arg0.name) < 0)
        return -1;

    else
        return 0;
}
// ===========================================================================================

public String toString() {
    return " " + this.num + " babies were named " + this.name;
}

}

1 个答案:

答案 0 :(得分:1)

每次从txt文件中读取新行时,您都会对两个arraylists进行排序。为什么?排序非常密集。特别是当您使用的那些txt文件很大时。

只需尝试将排序移出while循环。