Reputation: 1050
I have an ArrayList
of custom objects I called Questions
. These Questions
contain the question, a unique ID
, and an ArrayList
of Answers
. Now I'm trying to search for the question with a specific unique ID
. This is what I'm currently doing but I'm worried this might take too long for a big list, so I was wondering if there was a faster way to do this.
public Question getQuestion(String idLookingFor) {
for (Question question : questions) {
if (question.getId().equals(idLookingFor))
return question;
}
return null;
}
Upvotes: 2
Views: 175
Reputation: 13402
You can use HashMap
for storing the information about ID as key
and Question as value
. I am assuming, ID
is stored as Interger
.
Map<Integer, Question> map = new HashMap<>();
The Map
will provide you O(1)
time complexity for searching the question.
Upvotes: 5