saplingPro
saplingPro

Reputation: 21329

How does the contain method match?

Is the statement list.contains("are") (have commented it) being checked by matching character to character ?

import java.util.*;

class Tester {
    public static void main(String args[]) {
        String arr[] = {"how","are","you","veena"};
        LinkedList<String> list = new LinkedList<String>();
        for(String s : arr) {
            list.add(s);
        }
        if(list.contains("are")) { // STATEMENT
            System.out.println("Found !");
        }
    }
}

In this program if statement works. How does the contain method work ?

Upvotes: 0

Views: 72

Answers (2)

user902383
user902383

Reputation: 8640

this is implementations of method contains and indexOf from LinkedList

public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

   public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

so as you see it is iterating trough array till it finds first matching element

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

That method iterates over the linked list, and compare each element with the element passed by invoking equals() method. In this case, it will invoke String#equals(Object) method.

Upvotes: 2

Related Questions