What is the ArrayList.contains() method in Kotlin?
The kotlin.collections package is part of Kotlin’s standard library. It contains all collection types, including Map, List, Set, etc.
The package provides the ArrayList class, which is a mutable list. This class uses a dynamic resizable array as the backing storage.
The contains() method
The ArrayList class includes the contains() method which checks for the presence of the specified input element in the array list.
Syntax
fun contains(element: E): Boolean
Parameters
- This method takes the object to search in the array list as input.
Return value
This method returns true if the element is present in the list and false if the element is not present.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
It is allowed to contain duplicate elements.
The illustration below shows the function of the contains() method.
Code
The ArrayList class is present in the kotlin.collection package and is imported by default in every Kotlin program.
fun main(args : Array<String>) {val companyList = ArrayList<String>()companyList.add("Apple")companyList.add("Google")companyList.add("Microsoft")companyList.add("Netflix")println("Printing ArrayList elements--")println(companyList)println("Checking 'Microsoft' presence in array list using contains() : ${companyList.contains("Microsoft")}")println("Checking 'Adobe' presence in array list using contains() : ${companyList.contains("Adobe")}")}
Explanation
-
First, we create an empty
ArrayListto store the strings. -
Next, we add a few company names to the
ArrayListobject, using theadd()method such as:"Google","Apple","Microsoft", and"Netflix". -
Next, we call the
contains()method by passingMicrosoftas input and it returnstrue. -
We again call the
contains()method by passingAdobeas input and it returnsfalse.