[英]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.