Reputation: 15844
Let's say I have this simple class structure:
Vehicle
|-- Bus
`-- Car
Bus and Car extends Vehicle
I have List<Vehicle>
. How can I get only buses or cars? I would like to avoid instanceof
operator. Do I have to use Visitor pattern or is there any simpler solution?
Upvotes: 0
Views: 250
Reputation: 1766
If you don't want instanceOf add field to Vehicle that determine class.
Upvotes: -2
Reputation: 1503944
Well something will need to use instanceof
or an equivalent (such as Class.isInstance
).
Guava has a method which does exactly this though: Iterables.filter
. So you could use:
List<Bus> buses = Lists.newArrayList(Iterables.filter(vehicles, Bus.class));
Upvotes: 3
Reputation: 8458
I see no way to avoid the use of instanceof
operator in your case, nor can I see a way to produce much simpler code than this (without help from Guava) :
List<Bus> buses = new ArrayList<Bus>();
for (Vehicle v : vehicles)
if (v instanceof Bus)
buses.add(v);
Upvotes: 3