我有一个ArrayList我调用的自定义对象Questions.这些Questions包含的问题,唯一的ID和ArrayList的Answers.现在我正在尝试使用特定的唯一搜索问题ID.这就是我目前正在做的事情,但我担心这可能需要很长时间才能找到一个大清单,所以我想知道是否有更快的方法来做到这一点.
public Question getQuestion(String idLookingFor) {
for (Question question : questions) {
if (question.getId().equals(idLookingFor))
return question;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
您可以HashMap用来存储有关ID as key和的信息Question as value.我假设,ID存储为Interger.
Map<Integer, Question> map = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
这Map将为您提供O(1)搜索问题的时间复杂性.
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |