Java:从字典中延迟加载单词:如何使其静态最终?

标签 java final

我有一个使用单词列表的程序(例如/usr/share/dict/words 中的所有单词)。单词列表永远不会被修改,所以我想我应该将其设置为静态最终的。但我怎样才能最终完成呢?我当前的实现如下所示(我在需要时延迟加载单词列表,尽管我不确定延迟部分是否必要,因为列表并不是那么大或加载速度慢):

private static List<String> WORDS; // adding a final modifier doesn't work here

private static List<String> getWords() throws IOException {
  if (WORDS == null) {
    List<String> words = new LinkedList<String>();
    String line;
    BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
    while ((line = br.readLine()) != null) {
      words.add(line);
    }
    WORDS = words;
  }
  return WORDS;
}

在上面的代码中,我不允许将 WORDS final 。关于如何做到这一点有什么建议吗? (是否将其定为最终真的很重要吗?)

编辑:我想一种方法是通过以下方式:

private static final List<String> WORDS = getWords();

private static List<String> getWords() throws IOException {
  List<String> words = new LinkedList<String>();
  String line;
  try {
    BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
    while ((line = br.readLine()) != null) {
      words.add(line);
    }
  } catch (IOException e) {
    System.out.println("Error reading dictionary: " + e);
  }
  return words;
}

但这失去了延迟加载部分(尽管这可能并不像final那么重要?也许我太努力“按照书本”做事了?)。

最佳答案

您可以使用 ImmutableList来自Guava libraries以防止其被修改。

所以你可以这样做:

private static List<String> WORDS;

private static List<String> getWords() throws IOException {
  if (WORDS == null) {
    List<String> words = new LinkedList<String>();
    String line;
    BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
    while ((line = br.readLine()) != null) {
      words.add(line);
    }
    WORDS = ImmutableList.copyOf(words);
  }
  return WORDS;
}

关于Java:从字典中延迟加载单词:如何使其静态最终?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171995/

相关文章:

Java - 我的霍夫曼解压拒绝解压非文本文件(返回空文件)

java - 在命名空间 (, ) 中找到多个表 - SchemaExtractionException

java - 集合继承java vs groovy

swift - Swift 中的单例类是否需要 final?

java - 将 ScrollableComposite 位置设置为位置

java - 对象锁定私有(private)类(class)成员 - 最佳实践? ( java )

java - 接口(interface)方法中的最终参数 - 有什么意义?

java - 为什么静态初始化 block 中不允许有限定的静态最终变量?

java - 整数数组和关键字final。 [Java]

java - 内部类非final变量java