is it possible to determine the ArrayList-index of an element inside the ArrayList based on one of its attributes?
In my particular case I have an Object “worker” with the attributes “name” and “worker_id”. The worker_id is an ID I get from the database.
Since the first worker-object inside the ArrayList doesn’t necessarily start with 0 (and may have gaps), it’s not the same ID as the index each element has inside this ArrayList.
Now I want to determine this particular index of a worker-object inside the ArrayList based on its attribute “worker_id”. However: since the list can be very long, I’d like to not have to iterate over the worker-ArrayList everytime.
Using a HashMap might be a solution, but I’d like to use an ArrayList if possible, because I normally won’t need a key (except in this case).
Any suggestions are welcome!
Thank you in advance,
Igor.
It sounds to me that the list is at least sorted? In that case, you could use a binary search, which is slightly faster than a linear scan of the list.
Another option is to define two workers to be
equalif they have the sameworker_id. Then you could simply doint index = workerList.indexOf(new Worker(idToSearchFor));Well, to be honest, when I use a map it is seldom because I couldn’t do it with a list, but rather because the interface of a map is nicer to work with, and results in cleaner code. So, even though you may think that a HashMap is an overkill, it may be worth it, solely because it’s slightly more logical and the code ends up being a bit easier to read.