添加到TreeSet和HashSet的时间更快?

时间:2015-03-31 16:20:52

标签: java

我有一个TreeSet和一个HashSet,并希望打印出将.txt文件添加到它们所需的时间。 截至目前,我只能记录两者的时间,任何指导或协助。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Timer {
public static void main(String[] args) throws FileNotFoundException {

    Calendar    startTime    =    Calendar.getInstance();
    Set<String> hSet = new HashSet<String>();
    Set<String> tSet = new TreeSet<String>();

    try{
        File in = new File("C:\\Users\\Ceri\\Desktop\\war-and-peace.txt");
        Scanner s = new Scanner(in);
        while(s.hasNext()){
            String temp = s.next();
            hSet.add(temp);
            tSet.add(temp);
        }

    }catch(FileNotFoundException    e){
        System.out.println("File not found");
    }

    Calendar    endTime    =    Calendar.getInstance();
    double    consumedTime    =    (endTime.getTimeInMillis()    -
    startTime.getTimeInMillis())    /    1000.0;
    System.out.println("Consumed    time:"        +    consumedTime);

}

}

1 个答案:

答案 0 :(得分:0)

创建一个测试Set所用时间的函数,然后用各种集合调用它:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Timer {
    public static void main(String[] args) throws FileNotFoundException {
        test("HashSet time: " , new HashSet<String>());
        test("TreeSet time: " , new TreeSet<String>());
    }

    private void test(String label, Set set) {

        Calendar    startTime    =    Calendar.getInstance();

        try{
            File in = new File("C:\\Users\\Ceri\\Desktop\\war-and-peace.txt");
            Scanner s = new Scanner(in);
            while(s.hasNext()){
                String temp = s.next();
                set.add(temp);  // <==== Note
            }

        }catch(FileNotFoundException    e){
            System.out.println("File not found");
        }

        // (I didn't try to fix this truly bizarre indentation / line breaking)
        Calendar    endTime    =    Calendar.getInstance();
        double    consumedTime    =    (endTime.getTimeInMillis()    -
        startTime.getTimeInMillis())    /    1000.0;
        System.out.println(label        +    consumedTime);
    }
}

您可以通过其他方式改进它:

  1. 在将数据添加到Set之前,请先阅读文件一次,这样您就不会使用文件效果信息清除Set性能信息

  2. 让函数返回已用时间并显示增量

  3. 多次调用该函数,因此不只是每次执行一次,跟踪平均值/最差示例/最佳示例

  4. ......等等。