在HashMap或LinkedList中制作嵌套类的原因是什么? [英] What is the reason for making a nested class static in HashMap or LinkedList?
问题描述
在大多数情况下,我已经看到嵌套类是 static
。
In most of the cases I've seen that nested classes are static
.
让我们举个例子条目
类中 HashMap
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
.....
.....
}
或条目
LinkedList
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
.....
.....
}
到目前为止,关于嵌套类的知识是:
What I know so far about nested class is:
- 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中创建嵌套类的原因是什么?
My question is, what is the reason for making a nested class static in HashMap or LinkedList?
Update 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).
我认为这两点都回答了我的问题。感谢您的所有输入。
I think both these points answered my question. Thanks all for your input.
推荐答案
嵌套静态类不需要包含类的实例。这意味着你可以自己创建一个 HashMap.Entry
,而不必先创建一个 HashMap
根本不需要)。
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).
这篇关于在HashMap或LinkedList中制作嵌套类的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!