[英]Java using instanceof but based on method argument
I have 3 objects 我有3个物件
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: 传递给定的carType的最佳方式是什么(如果它是String或其他更好的方式),使其具有以下内容:
if (i instanceof carTypeGiven)
The method returns how many cars of specific type are available. 该方法返回可用的特定类型的汽车数量。
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>
您可以使用如下通配符将其限制为
Car
子类: Class<? extends Car>
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. 使用
Class.isInstance(Object)
确定车队中的汽车是否为所需类型。
It is also possible to do this more concisely with Java 8's streams (assuming fleet
is a collection): 也可以使用Java 8的流来更简洁地做到这一点(假设
fleet
是一个集合):
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: 如果
fleet
是一个数组,则需要做些微的不同:
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. 请注意,我将返回类型更改为
long
因为那是Stream.count()
返回的。 You could keep the return type as int
and cast the result from count()
to an int
, as well. 您可以将返回类型保留为
int
,并将结果从count()
转换为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.