Java教程是为JDK 8编写的。本页中描述的示例和实践不利用后续版本中引入的改进,并可能使用不再可用的技术。
请参阅Java语言更改,了解Java SE 9及后续版本中更新的语言特性的摘要。
请参阅JDK发布说明,了解所有JDK发布的新功能、增强功能和已删除或弃用选项的信息。
Set、List、Queue和Map。你不确定哪些实现会最好地工作,所以决定在实际情况下先使用通用实现。这些通用实现是哪些?Set: HashSetList: ArrayListQueue: LinkedListMap: HashMapSet实现,应该使用哪个类?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的时候。