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.
contains()
methodThe ArrayList
class includes the contains()
method which checks for the presence of the specified input element in the array list.
fun contains(element: E): Boolean
This method returns true
if the element is present in the list and false
if the element is not present.
ArrayList
follows the sequence of insertion of elements.
It is allowed to contain duplicate elements.
The illustration below shows the function of the contains()
method.
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")}")}
First, we create an empty ArrayList
to store the strings.
Next, we add a few company names to the ArrayList
object, using the add()
method such as: "Google"
, "Apple"
, "Microsoft"
, and "Netflix"
.
Next, we call the contains()
method by passing Microsoft
as input and it returns true
.
We again call the contains()
method by passing Adobe
as input and it returns false
.