Gipsy King
Gipsy King

Reputation: 186

What’s difference between equals and contains

I don’t know what is better to use , while I need to return boolean, searching for a match , using : contains or equals. Here are some examples.

List<String> names = new ArrayList<>();
names.add("John");
names.add("Laura");
names.add("Nick");

Equals :

boolean check;
for(String name : names)
{
 if("Laura".equals(name))
    { 
  check = true;
    }
}

Contains :

boolean check;
check = names.contains("Laura");
  1. What is actual difference ?
  2. What worth using ?

Thx for response in advance

Upvotes: 2

Views: 19669

Answers (2)

Rithesh B
Rithesh B

Reputation: 248

In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same then it returns true. If all characters are not matched then it returns false.

contains method -> returns true if the substring is present in the main string

For ex:

    String a = "Jarvis123";
    String b = "Jarvis";

    System.out.println(a.contains(b));  // will return true
    System.out.println(a.equals(b));    // will return false

Upvotes: 0

vs97
vs97

Reputation: 5859

The String equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. For your scenario, you would look through every String in your List, compare it with the String you want and return true if they are the same.

The ArrayList.contains(Object) method returns true if this List contains the specified element. The actual implementation of the contains method in java.util.ArrayList is the following:

/**
* Returns true iff element is in this ArrayList.
*
* @param e the element whose inclusion in the List is being tested
* @return true if the list contains e
*/
public boolean contains(Object e)
{
   return indexOf(e) != -1;
}

The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Whatever approach you decide to take, either is acceptable. In specifically your case, since you have a hard-coded value that you are checking, in my opinion it would look neater to use the contains method, but that is not a single correct answer.

Upvotes: 6

Related Questions