Reputation: 3204
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.
Upvotes: 6
Views: 26443
Reputation: 83008
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.
Upvotes: 5
Reputation: 13520
You can iterate through your ArrayList<String>
like
public String getWebsiteName(String toMatchString)
{
ArrayList<String> yourArrayList = new ArrayList<String>();
for (String webSiteName : yourArrayList)
{
if (webSiteName.contains(toMatchString))
return webSiteName;
}
return null;
}
and get the matching String
Upvotes: 1
Reputation: 12919
Use a helper function like this
public static boolean containsSubString(ArrayList<String> stringArray, String substring){
for (String string : stringArray){
if (string.contains(substring)) return true;
}
return false;
}
Upvotes: 0
Reputation: 157457
ArrayList.contains()
test the the String through equals. From the documentation:
public boolean contains(Object o) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
example:
boolean contains = yourArrayListInstance.contains(yourString);
Edit. If you want to check for substring you have to loop on the ArrayList's content and call String.contains
Upvotes: 4