Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of contains in Java ArrayList<String>

Tags:

java

arraylist

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?

like image 499
Mr Morgan Avatar asked Oct 15 '10 15:10

Mr Morgan


People also ask

Can I use contains for ArrayList?

contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.

Does ArrayList have Contains method in Java?

Java ArrayList contains()The contains() method checks if the specified element is present in the arraylist.

What is String contains () in Java?

Java String contains() Method The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.


3 Answers

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>();
like image 145
Andy Thomas Avatar answered Oct 29 '22 02:10

Andy Thomas


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.

like image 18
willcodejavaforfood Avatar answered Oct 29 '22 03:10

willcodejavaforfood


You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?

String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}

For reference, note that the following conditional will also execute if you append this code to the above:

String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}

Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.

like image 3
Michael McGowan Avatar answered Oct 29 '22 02:10

Michael McGowan