英文:
What is the difference between these two ways of creating a TreeMap (or any map)?
问题
我正在阅读一个项目中的一些代码,并遇到了这行代码:
private Map<String, Map<String, List<String>>> wordbatch;
在代码的后面,我在构造函数中看到了另一行代码:
wordbatch = new TreeMap<String, Map<String, List<String>>>();
这个单独的一行代码是否会产生相同的效果?:
Map<String, Map<String, List<String>>> wordbatch = new TreeMap<String, Map<String, List<String>>>();
这行代码与上面两行代码有什么区别?
非常感谢您的帮助。我想增强我对映射(maps)的了解。
英文:
I'm reading some code in a project and came across this line of code:
private Map<String, Map<String, List<String>>> wordbatch;
Further on in the code, I reached another line of code in the constructor:
wordbatch = new TreeMap<String, Map<String, List<String>>>;
Would this single line of code have the same effect?:
Map<String, Map<String, List<String>>> wordbatch = new TreeMap<String, Map<String, List<String>>>();
What are the differences in this line of code and the two lines of code above?
Any help is appreciated, and thank you so much. Trying to enhance my knowledge about maps.
答案1
得分: 2
有一些细微差别在你提供的语句之间。
在第一种情况下,你在第 X 行声明了一个实例变量(其值为 null
),并且在代码的某个地方,第 Y 行,你给它另一个值,一个新的映射。
在第二种情况下,你既在声明它又在给它一个值。然而,重要的是这是在哪里发生的。
-
如果你将完整的声明放在原始声明的位置,即第 X 行,那么它仍然是一个实例变量。但是,
- 你忘记了加上
private
。如果你不希望同一包中的其他类直接使用这个变量,这可能很重要。 - 如果代码中有任何部分依赖于这个变量在开始时可能为 null(查找检查该变量是否为 null 的代码),那么通过在声明中初始化它可能会引入错误。
- 你忘记了加上
-
如果你将声明放在原始的赋值位置,即第 Y 行,那么你就不再在声明一个实例变量。这将成为一个局部变量。代码的其余部分,它期望这个实例变量存在,将产生编译错误。实例变量必须在任何方法或构造函数之外声明。
请注意,如果第 Y 行在你的构造函数中,并且它是唯一的构造函数,那么在这两种初始化方式之间几乎没有什么区别。
英文:
There are a few subtle differences between the statements you presented.
In the first case, you are declaring an instance variable (whose value is null
) on line X, and somewhere in the code on line Y, you give it another value, a new map.
In the second case, you are both declaring and giving it a value. However, it's important where this is happening.
- If you put that full declaration where the original declaration was, on line X, then it's still an instance variable. However,
- You forgot your
private
. This may be important if you don't want other classes in the same package to use that variable directly. - If there is any part of the code that relies on the fact that this variable may be null in the beginning (look for code that checks if this variable is null), then you may be introducing a bug by initializing it in the declaration.
- You forgot your
- If you put that declaration where the original assignment was, on line Y, then you are no longer declaring an instance variable. This becomes a local variable. The rest of the code, which expects this instance variable to exist, will produce compilation errors. An instance variable must be declared outside of any method or constructor.
Note that if line Y is in your constructor, and it's the only constructor, then there is very little difference in the two ways of initializing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论