Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
Set,List,Queue 和 Map。你不确定哪种实现最有效,因此你决定使用通用实现,直到你更好地了解你的程序在现实世界中的工作方式。这些是哪些实现?Set: HashSetList: ArrayListQueue: LinkedListMap: HashMap
Set 实现,你应该使用哪个类? TreeSet 保证有序集合按元素顺序排列,根据元素的自然顺序或提供的 Comparator 进行排序。Collections 类,它提供操作或返回集合的静态方法。List。然后程序应该从文件中打印随机行,打印的行数由第二个命令行参数指定。编写程序,以便一次性分配正确大小的集合,而不是在读入文件时逐渐扩展。提示:要确定文件中的行数,请使用 java.io.File.length 来获取文件的大小,然后除以假定的大小平均线。 List,我们将使用 ArrayList。我们通过取文件大小并除以 50 来估计行数。然后我们将这个数字翻倍,因为高估比低估更有效。
import java.util.*;
import java.io.*;
public class FileList {
public static void main(String[] args) {
final int assumedLineLength = 50;
File file = new File(args[0]);
List<String> fileList =
new ArrayList<String>((int)(file.length() / assumedLineLength) * 2);
BufferedReader reader = null;
int lineCount = 0;
try {
reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null;
line = reader.readLine()) {
fileList.add(line);
lineCount++;
}
} catch (IOException e) {
System.err.format("Could not read %s: %s%n", file, e);
System.exit(1);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {}
}
}
int repeats = Integer.parseInt(args[1]);
Random random = new Random();
for (int i = 0; i < repeats; i++) {
System.out.format("%d: %s%n", i,
fileList.get(random.nextInt(lineCount - 1)));
}
}
}
ArrayList 对其性能几乎没有影响。当程序重复创建大型 ArrayList 对象而不干预 I/O 时,预先指定初始容量更有用。