簡體   English   中英

奇怪的問題讀到樹集

[英]Weird Issue reading to a TreeSet

我似乎有一個奇怪的問題,即它是更快讀取一個文件到一個ArrayList ,並從ArrayList讀取到一個TreeSet ,而不是直接將數據添加到TreeSet 我似乎無法理解問題。

public TreeSet<String> readFile(){
    TreeSet<String> dict = null;
    try {
        dict = new TreeSet<String>();
        BufferedReader in = new BufferedReader(new InputStreamReader(getAssets().open("dictionary")));
        String line;

        while ((line = in.readLine()) != null) {
            line = line.split(SEPARATOR)[0];
            dict.add(line);
        }

    }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
    }

    return dict;
}

同樣,此問題似乎與拆分功能有關,因為如果沒有拆分功能,它會以正常速度運行。
我的輸入文件大約有16萬行。
帶有TreeSet的ArrayList大約需要2000毫秒。
TreeSet需要大約10萬毫秒。

ArrayList-> TreeSet代碼

public TreeSet<String> readFile(){
    ArrayList<String> dict = null;
    try {
        dict = new ArrayList<String>();
        BufferedReader in = new BufferedReader(new InputStreamReader(getAssets().open("dictionary")));
        String line;
        while ((line = in.readLine()) != null) {
            line = line.split(SEPARATOR)[0];
            dict.add(line);
        }
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    TreeSet<String> tree = new TreeSet<String>();
    for(String word:dict){
        tree.add(word);
    }
    return tree;
}

當前使用OnePlus One和Cyanogenmod進行測試。

TreeSet使用在String定義的Comparable ,並將嘗試進行n次排序->要添加的String的大小。

ArrayList僅按索引添加,並且沒有任何后台操作在運行。

一旦到達,所有TreeSet都必須按照定義的規則進行排序。

此處定義: API

Costs guaranteed log(n) for basic operations

我猜您正在讀取已排序的文件。 然后立即插入將傾向於創建線性列表,或者需要連續重新平衡樹以防止這種情況。

TreeSet.addAll(Collection)首先進行排序(對於排序后的列表而言相對較快),然后使用優化的算法,知道對元素進行排序以構建(平衡)樹。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM