存储某些类JAVA的子类的哈希集合 [英] Hash set that stores subclasses of certain class JAVA
问题描述
考虑以下情况:
Consider the following situation:
public abstract class Vegetable {};
public class Tomato extends Vegetable {};
public class Cucumber extends Vegetable {};
public class Orange {};
关键是 - 我希望我的 HashSet
只存储延伸 Vegetable
的东西,我该怎么做?这应该很简单..
The point is - I want my HashSet
to store only something extending Vegetable
, how do I do this? This should be simple..
..但设置<?延伸蔬菜> ()hs = new HashSet <?延伸蔬菜> ();
当然不是一个工作构造,Java希望我指定什么类型的 Set
我想要 - Tomato
或 Cucumber
,如果我只是想要蔬菜吗?
..but Set <? extends Vegetable> () hs = new HashSet <? extends Vegetable> ();
is not a working construction of course, Java wants me to specify what type of Set
I want - Tomato
or Cucumber
, what if I just want anything vegetable?
我宁愿不要使用任何强制转换...
I'd rather not to use any casts...
推荐答案
当您创建
When you create
Set<SomeType> = new HashSet<SomeType>();
该集合能够存储属于的任何子类的对象SomeType
。在你的情况下,你需要的只是
the set is capable of storing objects that belong to any subclass of SomeType
. In your case, all you need is
Set<Vegetable> set = new HashSet<Vegetable>();
您现在可以这样做:
You can do this now:
set.add(new Tomato());
set.add(new Cucumber());
这样做会触发编译错误:
Doing this will trigger a compile error:
set.add(new Orange()); // Does not compile
就铸造而言,您不需要在其上投射对象进入集合
。但是,如果您需要特定类型(即不是简单地 Vegetable
),则需要进行转换。
As far as casts go, you wouldn't need to cast objects on their way into the set
. However, if you need a specific type (i.e. not simply Vegetable
) on retrieval, you would need a cast.
这篇关于存储某些类JAVA的子类的哈希集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!