java - Is there a way I can check if any of the objects in an ArrayList have an object of a specific class?
问题描述
Assuming I have a class hierarchy where Monkey, Chimp, and Ape classes all inherit from an Animal Class. I now have an ArrayList where some random number of monkeys/chimps/apes are stored inside. Is there a function that can check if any Monkeys exist in that arraylist? Right now I have
for (Animal animal1 : Enclosure.HABITABLE_ANIMALS)
{
if (animal.getClass().equals(animal1.getClass()))
{
count++;
}
}
and if the count is greater than 0 it returns true (in this code you HABITABLE_ANIMALS is the arraylist of animals, and animal is the Monkey) surely there is a more efficient and better way of doing this
解决方案
There is no more efficient way to do this unfortunately, since you'll need to go through the whole List
anyway (time complexity: O(n)
)
However, there might be a more expressive way of doing it using Stream
(but it adds the overhead of creating a Stream
).
If expressiveness is more important than performance, I'd suggest to go for this solution
Enclosure.HABITABLE_ANIMALS
.stream()
.anyMatch(animal.getClass()::isInstance)
推荐阅读
- ios - 在 ContainerView 中打开不同的视图
- angular - 使用 amexio 开发 Angular 应用程序
- angular - 我应该在 Jasmine 3 中使用什么来代替 fit 和 fdescribe?
- ios - Swift:使用 UIButtons 作为 UIImages
- python - NumPy 读取/写入文件性能(特别是 ndarray.tofile)
- mysql - 转换 '1|2|India' 将此管道分隔的字符串设置为列
- labview - 如何在LabVIEW中对同一个控件进行多个属性读取和写入?
- objective-c - Objective-c:使用块的方法如何返回对象
- python-3.x - Python Pandas Dataframe 用同一会话的另一个单元格的值替换单元格值
- azure - Azure 中的 CORDA 节点配置