问题
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