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

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

    There are three basic options:

    1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

    2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

    3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

    Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

    • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

    • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

    • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

    • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

提交回复
热议问题