我已经用 Python 编写了几个月的代码,现在由于工作相关原因我不得不切换到 Java。我的问题是,有一种方法可以模拟这种语句
if var_name in list_name:
# do something
没有定义一个额外的 isIn()
-like boolean 函数来扫描 list_name
以找到 var_name
?
最佳答案
您正在寻找 List#contains
这是继承自 Collection#contains
(因此您也可以将它与 Set
对象一起使用)
if (listName.contains(varName)) {
// doSomething
}
列表#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)).
如您所见,List#contains
使用 equals
返回 true 或 false。强烈建议在您正在创建的类中使用 @Override
此方法以及 hashcode
。
关于java - 在 Java 中模拟 if-in 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38182463/