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 way, given those two fields, to see if the array contains that object.The wrench is that these classes are generated based on XSD objects, so I can't modify the classes themselves to overwrite the .equals.Is there any better way than just looping through and manually comparing the two fields for each object and then breaking when found? That just seems so messy, looking for a better way.Edit: the ArrayList comes from a SOAP response that is unmarshalled into objects. 解决方案 It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.If you really need very efficient look-up speeds at all cost, you'll need to do two things:Work around the fact that the classis generated: Write an adapter class whichcan wrap the generated class andwhich implement equals() basedon those two fields (assuming theyare public). Don't forget to alsoimplement hashCode() (*)Wrap each object with that adapter andput it in a HashSet.HashSet.contains() has constantaccess time, i.e. O(1) instead of O(n).Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.*() Implementing hashCode() is best done by XOR'ing (^ operator) the hashCodes of the same fields you are using for the equals implementation (but multiply by 31 to reduce the chance of the XOR yielding 0) 这篇关于在 Java 中查看 ArrayList 是否包含对象的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!