I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement
if var_name in list_name:
# do something
without defining an additional isIn()
-like boolean function that scans list_name
in order to find var_name
?
You're looking for List#contains
which is inherited from Collection#contains
(so you can use it with Set
objects also)
if (listName.contains(varName)) {
// doSomething
}
List#contains
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
As you see, List#contains
uses equals
to return true or false. It is strongly recommended to @Override
this method in the classes you're creating, along with hashcode
.
You can use List.contains(object), but make sure your class which you have used to create list, is implementing equals for proper equals check. Otherwise you will be able to only get two objects equal only if object itself is same.
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