这两个java变量声明有什么区别? [英] What's the difference between these two java variable declarations?
问题描述
public class SomeClass {
private HashSet<SomeObject> contents = new HashSet<SomeObject>();
private Set<SomeObject> contents2 = new HashSet<SomeObject>();
}
有什么区别?最后他们都是 HashSet
不是吗?第二个看起来对我来说是错的,但我已经看到它经常使用,接受和工作。
What's the difference? In the end they are both a HashSet
isn't it? The second one looks just wrong to me, but I have seen it frequently used, accepted and working.
推荐答案
Set
是一个接口, HashSet
是一个实现 Set
接口的类。
Set
is an interface, and HashSet
is a class that implements the Set
interface.
将变量声明为类型 HashSet
表示没有其他实现 Set 可以使用code>。如果您需要
HashSet
的特定功能,您可能需要这样做。
Declaring the variable as type HashSet
means that no other implementation of Set
may be used. You may want this if you need specific functionality of HashSet
.
如果您不需要来自<的任何特定功能code> HashSet ,最好将变量声明为类型 Set
。这使得确切的实现可以在以后更改。您可能会发现,对于您正在使用的数据,不同的实现可以更好地工作。通过使用界面,您可以在以后需要时进行此更改。
If you do not need any specific functionality from HashSet
, it is better to declare the variable as type Set
. This leaves the exact implementation open to change later. You may find that for the data you are using, a different implementation works better. By using the interface, you can make this change later if needed.
您可以在此处查看更多详细信息:我什么时候应该在java中使用接口?
You can see more details here: When should I use an interface in java?
这篇关于这两个java变量声明有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!