Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check arraylist contains this particular word in android?

I have ArrayList<String> in that I added 3-4 website names. Like, http://www.google.com, https://www.stackoverflow.com, etc. Now in my application if I type simply "google" then I want to compare that "google" word with the ArrayList<String>.

I am stuck here. Can anyone tell me how can I compare the string with the array object?

Thanks in advance.

like image 637
anddev Avatar asked Feb 12 '14 10:02

anddev


1 Answers

To do so, you need to override implementation of contains(). I am giving you a simple example.

Custom ArrayList class

public class MyArrayList extends ArrayList<String> {
    private static final long serialVersionUID = 2178228925760279677L;

    @Override
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    @Override
    public int indexOf(Object o) {
        int size = this.size(); 
        if (o == null) {
            for (int i = 0; i < size ; i++) {
                if (this.get(i) == null) {
                    return i; 
                }
            }
        } else {
           for (int i = 0; i < size ; i++) {
                if (this.get(i).contains(String.valueOf(o))) {
                    return i; 
                }
            }
        }
        return -1;
    }
}

How to use

MyArrayList arrayList = new MyArrayList(); 
arrayList.add("http://www.google.com");
arrayList.add("https://www.stackoverflow.com");
arrayList.add("http://pankajchunchun.wordpress.com");

if (arrayList.contains("google")) {
    System.out.println("ArrayList Contains google word");
}

if (arrayList.contains("igoogle")) {
    System.out.println("ArrayList Contains igoogle word");
} else {
    System.out.println("ArrayList does not Contains igoogle word");
}

Below is output for above code example

ArrayList Contains google word
ArrayList does not Contains igoogle word

See ArrayList Source Code for more custom implementation.

like image 73
Pankaj Kumar Avatar answered Sep 22 '22 21:09

Pankaj Kumar