Contains and equals in java

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Java hashCode() and equals() Contract for the contains(Object o) Method of Set

The article is about hashCode and equals contract used for the contains(Object o) method in Set.

A puzzle about using the contains() method from Set

import java.util.HashSet; class Dog{ String color; public Dog(String s){ color = s; } } public class SetAndHashCode { public static void main(String[] args) { HashSetDog> dogSet = new HashSetDog>(); dogSet.add(new Dog("white")); dogSet.add(new Dog("white")); System.out.println("We have " + dogSet.size() + " white dogs!"); if(dogSet.contains(new Dog("white"))){ System.out.println("We have a white dog!"); }else{ System.out.println("No white dog!"); } } }

import java.util.HashSet; class Dog < String color; public Dog(String s)< color = s; >> public class SetAndHashCode < public static void main(String[] args) < HashSetdogSet = new HashSet(); dogSet.add(new Dog("white")); dogSet.add(new Dog("white")); System.out.println("We have " + dogSet.size() + " white dogs!"); if(dogSet.contains(new Dog("white")))< System.out.println("We have a white dog!"); >else < System.out.println("No white dog!"); >> >

We add two white dogs to the set — dogSet, and the size shows we have 2 white dogs. But why there is no white dog when we use contains() method?

The contains(Object o) method of Set

From Java Doc, the contains() method returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)). So the contains() method actually use equals() method to check equality.

Note that null can be added to a set as an element. The following code actually prints true.

HashSetDog> a = new HashSetDog>(); a.add(null); if(a.contains(null)){ System.out.println("true"); }

HashSet a = new HashSet(); a.add(null); if(a.contains(null))

The public boolean equals(Object obj) method is defined in the Object class. Every class(including classes defined by yourself) has Object as a superclass and it is the root of any class hierarchy. All objects, including arrays, implement the methods of this class.

In the class defined by yourself, if you don’t explicitly override this method, it will have a default implementation. It returns true if and only if two objects refer to the same object, i.e., x == y is true.

If we change the Dog class to the following, will it work?

class Dog{ String color; public Dog(String s){ color = s; } //overridden method, has to be exactly the same like the following public boolean equals(Object obj) { if (!(obj instanceof Dog)) return false; if (obj == this) return true; return this.color.equals(((Dog) obj).color); } }

Now the problem is caused by the hashCode and equals contract in Java. The hashCode() method is another method in Object class.

The contract is that if two objects are equal(by using equals() method), they must have the same hashCode(). If two objects have same hash code, they may be not equal.

The default implementation of public int hashCode() returns distinct integers for distinct objects. In this particular example, because we haven’t defined our own hashCode() method, the default implementation will return two different integers for two white dogs! This breaks the contract.

Solution for the contains() method in Set

class Dog{ String color; public Dog(String s){ color = s; } //overridden method, has to be exactly the same like the following public boolean equals(Object obj) { if (!(obj instanceof Dog)) return false; if (obj == this) return true; return this.color.equals(((Dog) obj).color); } public int hashCode(){ return color.length();//for simplicity reason } }

Источник

What are the differences between equals and contains in java?

Equals checks if a string is equal to the specified object. Contains check if your specified string is part the string you referenced to. You use equals to check the string values of one object from another if they are pointing to different instances, say this code for example: str1 = «Hello World!»; str2 = str1; if (str1 == str2) < return true; >else < return false; >This will return true, however: String str1 = «Hello World!»; String str2 = «Hello World!»; if (str1 == str2) < return true; >else < return false; >. would return false, for these strings may be the same, but they have different instances. To counter this, we use the equals method: str1 = «Hello World!»; str2 = «Hello World!»; if (str1.equals(str2)) < return true; >else < return false; >This would return true again! Finally, contains checks if a specified string is part of the string you compared it to, something like this: String str1 = «Hello World!» String str2 = «Hello World» String comp = «!» boolean compare1 = str1.contains(comp); boolean compare2 = str2.contains(comp); Compare1 would return true, since there is an exclamation point in str1! And compare2 would return false, since there is no exclamation point in the string. The exclamation point is referenced by the comp variable.

equals method will return true only if the objects compared are the same (same==same) but contains method returns true if the second string is contained in the first one : char y =»yellow»; y.contains(low); // that will return true.

Thank you so much guys. I appreciated your replies. Now, things was more clearer. I was confused that’s why. Btw, thanks again 🙂

Often have questions like this?

Learn more efficiently, for free:

Источник

Оцените статью