Most efficient way to see if an ArrayList contains an object in Java

后端 未结 12 1142
孤城傲影
孤城傲影 2020-11-30 18:25

I have an ArrayList of objects in Java. The objects have four fields, two of which I\'d use to consider the object equal to another. I\'m looking for the most efficient wa

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 19:24

    If you need to search many time in the same list, it may pay off to build an index.

    Iterate once through, and build a HashMap with the equals value you are looking for as the key and the appropriate node as the value. If you need all instead of anyone of a given equals value, then let the map have a value type of list and build the whole list in the initial iteration.

    Please note that you should measure before doing this as the overhead of building the index may overshadow just traversing until the expected node is found.

提交回复
热议问题