在对象数组中找到对象变量的特定值的最快方法

sil*_*oid 2 java

我有一个ArrayList我调用的自定义对象Questions.这些Questions包含的问题,唯一的IDArrayListAnswers.现在我正在尝试使用特定的唯一搜索问题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)

You*_*bit 5

您可以HashMap用来存储有关ID as key和的信息Question as value.我假设,ID存储为Interger.

Map<Integer, Question> map = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

Map将为您提供O(1)搜索问题的时间复杂性.