Hash set that stores subclasses of certain class JAVA

怎甘沉沦 提交于 2019-12-13 13:12:34

问题


Consider the following situation:

public abstract class Vegetable {};

public class Tomato extends Vegetable {};
public class Cucumber extends Vegetable {};

public class Orange {};

The point is - I want my HashSet to store only something extending Vegetable, how do I do this? This should be simple..

..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...


回答1:


When you create

Set<SomeType> = new HashSet<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

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.



来源:https://stackoverflow.com/questions/17008511/hash-set-that-stores-subclasses-of-certain-class-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!