问题

1.问:你打算写一个使用几个基本集合接口的程序:SetListQueue,和Map。您不确定哪种实现效果最佳,因此您决定使用通用实现,直到更好地了解程序在现实世界中的工作方式。这些是哪些实现?
答:

  1. Set: HashSet
  2. List: ArrayList
  3. Queue: LinkedList
  4. Map: HashMap

2.问题:如果您需要一个提供按值排序的迭代的Set实现,则应使用哪个类?
答案:
TreeSet保证排序后的集合按元素的升序排列,根据元素的自然顺序或Comparator提供的元素进行排序。
3.问题:您使用哪个类访问包装器实现?
答:
您使用Collections类,该类提供可对集合进行操作或返回集合的静态方法。

练习题

1.练习:编写一个程序,该程序将第一个命令行参数指定的文本文件读入List。然后,程序应从文件中打印随机行,即第二个命令行参数指定的打印行数。编写程序,以便一次分配所有正确大小的集合,而不是在读取文件时逐渐扩展它。提示:要确定文件中的行数,请使用 java.io.File.length获取文件的大小,然后除以假设的平均线尺寸。
答:
由于我们是随机访问List,因此我们将使用ArrayList。我们通过将文件大小除以50来估计行数。然后我们将该数字加倍,因为高估比低估更有效。

  1. import java.util.*;
  2. import java.io.*;
  3. public class FileList {
  4. public static void main(String[] args) {
  5. final int assumedLineLength = 50;
  6. File file = new File(args[0]);
  7. List<String> fileList =
  8. new ArrayList<String>((int)(file.length() / assumedLineLength) * 2);
  9. BufferedReader reader = null;
  10. int lineCount = 0;
  11. try {
  12. reader = new BufferedReader(new FileReader(file));
  13. for (String line = reader.readLine(); line != null;
  14. line = reader.readLine()) {
  15. fileList.add(line);
  16. lineCount++;
  17. }
  18. } catch (IOException e) {
  19. System.err.format("Could not read %s: %s%n", file, e);
  20. System.exit(1);
  21. } finally {
  22. if (reader != null) {
  23. try {
  24. reader.close();
  25. } catch (IOException e) {}
  26. }
  27. }
  28. int repeats = Integer.parseInt(args[1]);
  29. Random random = new Random();
  30. for (int i = 0; i < repeats; i++) {
  31. System.out.format("%d: %s%n", i,
  32. fileList.get(random.nextInt(lineCount - 1)));
  33. }
  34. }
  35. }

该程序实际上将大部分时间都花在读取文件上,因此预先分配ArrayList对其性能几乎没有影响。当程序在不干预I / O的情况下重复创建大的ArrayList对象时,预先指定初始容量可能会很有用。