简体   繁体   中英

Java Linked List .contains method

I have a LinkedList containing elements of type A. I need to check whether the list contains an element based on some criteria.

Is it enough to override the .equals method in class A, or do I need to override the hash method as well?

You need to override the hashCode() method when your Object will be used in data structures that use hashes. HashMap, HashSet, etc.

Nothing is saying that you must implement the hashCode() function. Many data structures only use the equals() method, not the hashCode() function, so you can get away with not implementing it.

But you can't really guarantee that nobody will ever put it into another data structure that does use the hashCode() function, so it's probably a good habit to just implement it from the start.

You don't HAVE to override hashCode, but equal Objects should have the same hashcode. My advice: If you use eclipse, rightclick on the class, go to source, generate equals() and hashcode(), and select the variables that have to be equal. Its the easiest way.

The equals() method should be used only to tell what the object's identity is.

If the criteria used to find the object you're looking for match perfectly those used to define the object's identity, then it is just fine to call List 's contains() method, which relies on equals() .

In any other case, you should rather loop over the list and perform manual comparisons. Or alternatively, you use Java8 Streams, which offer filtering functions.

You must be aware that by implementing the equals method, you're defining an equivalence relation, ie one that subdivides all objects of this class into equivalence classes. When there are many objects that fulfill your criteria, they would all be considered equal and they would all have to have the same hashCode. As a consequence, when you put those objects in a HashMap at some point, all these objects would end up in the same slot, leading to a degenerated HashMap that would perform badly.

Even if you do not plan to put your objects in a HashMap, this seems to be a strong argument against implementing equals to compare based on a broader criteria.

You have to make sure that your implementation fulfills the contact of equivalence, that is, it must be reflexive, symmetric, and transitive. Joshua Bloch's standard book " Effective Java " has a detailed explanation.

You have to implement hashCode whenever you implement equals , because every two objects that are equal must have the same hash code (see this post for a detailed explanation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM