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

后端 未结 12 1144
孤城傲影
孤城傲影 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:21

    If the list is sorted, you can use a binary search. If not, then there is no better way.

    If you're doing this a lot, it would almost certainly be worth your while to sort the list the first time. Since you can't modify the classes, you would have to use a Comparator to do the sorting and searching.

提交回复
热议问题