tania
tania

Reputation: 1086

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 {};

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

Upvotes: 5

Views: 2374

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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.

Upvotes: 8

Related Questions