Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 319
tania Avatar asked Jun 09 '13 10:06

tania


1 Answers

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.

like image 191
Sergey Kalinichenko Avatar answered Nov 15 '22 10:11

Sergey Kalinichenko