ArrayList & contains() - case insensitive
I want the contains() method from ArrayList to be case insensitive.
Is开发者_如何学C there any way?
Thanks
No. You will have to define your own contains method that will have to iterate among the ArrayList
and compare the values using the equalsIgnoreCase
method of the String
class.
Edit: I don't want to be rude, but the question is pretty clear: the guy wants to use the contains
method. So he can't/should use toLowerCase
before adding the elements because of too many reasons: for example, he could need the original String
(not the one that is lowercased). Also, as we are talking about the contains
method, we are focusing on the elements rather than their indexes (as someone answered some minutes ago).
As @Cristian has said, there is no native method to achieve this. I thought I'd post the small utility method that I wrote in case it's a useful copy-and-paste:
public static boolean ContainsCaseInsensitive(ArrayList<String> searchList, String searchTerm)
{
for (String item : searchList)
{
if (item.equalsIgnoreCase(searchTerm))
return true;
}
return false;
}
I had a problem like this, and I used this workaround with BinarySearch that seems to work:
ArrayList al= new ArrayList();
al.Add("Elem1");
al.Add("Elem5");
al.Add("Elem3");
al.Sort();
if (al.BinarySearch("elem3", new CaseInsensitiveComparer()) > 0)
MessageBox.Show("Exists"); //this case
else
MessageBox.Show("Not found");
精彩评论