I have an if
statement:
if (inventory.contains("bread"))
But now I want to check
inventory
contains "bread"How can I do this?
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.
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
Contains(Char) Returns a value indicating whether a specified character occurs within this string. Contains(String) Returns a value indicating whether a specified substring occurs within this string. Contains(Char, StringComparison)
The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not. Parameters: This method accepts a single parameter obj whose presence in this list is to be tested.
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) { // do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With