java - Getting first element of specific type from ArrayList -
I have ArrayList type
Animal . There are 10 references to objects in this list, which are 3 dogs, 3 cats and 4 birds. All three types (
dogs ,
cat and
birds ) get from
animals . Order of animals
Is there a more efficient way to get the first
Cat from the list and use the
instanceof operator?
Example.
cat cat = null; (Animal animal: list of animals) {if (animal for example cat) {cat = animal; break; }}
No, the actions you need to complete are as many as Quickly it happens: Searching for a particular ArrayList is always linear (i.e. O (n) ).
In the context of readability, however, you can improve it by hiding the search in a supportive method, which takes a list and type, and finds the first occurrence of this type:
public stable If you need to go faster than your search, you will need a different data structure.
Comments
Post a Comment