Question

Use of contains in Java ArrayList<String>

If I have an ArrayList of String forming part of a class in Java like so:

private ArrayList<String> rssFeedURLs;

If I want to use a method in the class containing the above ArrayList, using ArrayList contains to check if a String is contained in this ArrayList, I believe I should be able to do so as follows:

if (this.rssFeedURLs.contains(rssFeedURL)) {

Where rssFeedURL is a String.

Am I right or wrong?

 45  152609  45
1 Jan 1970

Solution

 72

You are right. ArrayList.contains() tests equals(), not object identity:

returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:

private List<String> rssFeedURLs = new ArrayList<String>();
2010-10-15

Solution

 18

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

2010-10-15