Reputation:
I have 3 objects
Car
SmallCar extends Car
LargeCar extends Car
Using this method i want to count cars of specific type in a list:
public int availableCars(String carType) {
int count = 0;
for (Car i : fleet) {
if (i instanceof SmallCar) {
count++;
}
}
return count;
}
What is the best way to pass the carType given (if it is as String or something else that would be better) to have something like:
if (i instanceof carTypeGiven)
The method returns how many cars of specific type are available.
Upvotes: 0
Views: 1146
Reputation: 16409
Pass in the class instead of a string indicating the desired type. You can limit it to subclasses of Car
using wildcards like this: Class<? extends Car>
public int availableCars(Class<? extends Car> carType) {
int count = 0;
for (Car car : fleet) {
if (carType.isInstance(car)) {
count++;
}
}
return count;
}
Use Class.isInstance(Object)
to determine if a car in the fleet is of the desired type.
It is also possible to do this more concisely with Java 8's streams (assuming fleet
is a collection):
public long availableCars(Class<? extends Car> carType) {
return fleet.stream().filter(carType::isInstance).count();
}
If fleet
is an array, you would need to do it slightly differently:
public long availableCars(Class<? extends Car> carType) {
return Arrays.stream(fleet).filter(carType::isInstance).count();
}
Note that I have changed the return type to long
since that's what Stream.count()
returns. You could keep the return type as int
and cast the result from count()
to an int
, as well.
Upvotes: 2