【问题标题】:What is the reason for making a nested class static in HashMap or LinkedList? [duplicate]在 HashMap 或 LinkedList 中将嵌套类设为静态的原因是什么? [复制]
【发布时间】:2015-07-21 16:41:26
【问题描述】:

在大多数情况下,我看到嵌套类是static

让我们以HashMap 中的Entry 类为例

static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    final int hash;

    .....
    .....
}

或者EntryLinkedList

private static class Entry<E> {
    E element;
    Entry<E> next;
    Entry<E> previous;

    .....
    .....
}

到目前为止,我对嵌套类的了解是:

- A non-static nested class has full access to the members of the class 
  within which it is nested.

- A static nested class cannot invoke non-static methods or access non-
  static fields

我的问题是,在 HashMap 或 LinkedList 中将嵌套类设为静态的原因是什么?

更新 1:

Following the already answer link I got an answer - Since And since it does not need 
access to LinkedList's members, it makes sense for it to be static - it's a much 
cleaner approach.

Also as @Kayaman pointed out: A nested static class doesn't require an instance of 
the enclosing class. This means that you can create a HashMap.Entry by itself, 
without having to create a HashMap first (which you might not need at all).

我认为这两点都回答了我的问题。谢谢大家的意见。

【问题讨论】:

  • 哦!我在寻找答案时没有意识到它是重复的。

标签: java linked-list hashmap nested-class


【解决方案1】:

嵌套的静态类不需要封闭类的实例。这意味着您可以自己创建HashMap.Entry,而不必先创建HashMap(您可能根本不需要)。

【讨论】:

  • 那么,将嵌套类设为静态(并且可能是私有的)总是一种好习惯吗?
  • @Kartic - 不。不是总是。我通常会避开嵌套类,除非它们确实需要。嵌套类的使用基于设计决策Entry 是一个嵌套类,因为像Arrays 这样的其他类也有自己的Entry定义静态嵌套类通常用于(打包问题)使您的代码更具可读性
【解决方案2】:

1) 因为“外部”不需要它:它只被封闭类使用。通过将其设为private 内部静态类,这种意图是显而易见的。

2) 作为一个内部类,它可以自动访问封闭类的所有 private 字段,因此无需创建 getter 或更糟糕的方法,比如将它们封装为私有或 protected

为什么要用static

非静态内部类需要对封闭类实例的引用。如果内部类是static,则不需要:static 内部类的实例没有对封闭类的引用。它们可以在没有封闭类型的实例的情况下创建,并且它们可以在没有它的情况下生存。

在非静态内部类的情况下,封闭类的实例有时是透明的(例如,当您从封闭类的非静态方法实例化非静态内部类时,它是this),或者可以是明确的,例如:

EnclosingClass ec = new EnclosingClass();
InnerClass ic = ec.new InnerClass();

【讨论】:

  • 问题似乎是在问“为什么要让它们成为静态”,而不是“为什么要让它们成为私有”
  • 问题是,我们为什么要让它成为静态的,你的答案中没有提到这一点
  • @khelwood 抱歉,忘记了。编辑了问题以包含它。
猜你喜欢
  • 2011-08-13
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2013-10-25
  • 2012-12-31
相关资源
最近更新 更多