有多个值,要么都为空,要么都不为空,有什么比较好的写法
你是想要这样的东西?
public static void main(String[] args) {
allNull(null, null, null);
}
public static boolean allNull(Object... args) {
if (args == null || args.length == 0) {
throw new RuntimeException("input is empty");
}
for (Object arg : args) {
if (arg != null) {
return false;
}
}
return true;
}python中有个all方法
其它语言其实也可以用位运算的方式实现:
<?php
function all($data)
{
if (!is_array($data)) {
$data = array($data);
}
$result = 1;
foreach ($data as $item) {
$result &= intval(boolval($item));
}
return boolval($result);
}如果为空转成0,不为空转成1,做&运算,最后再转成bool型。
4 回答968 阅读
4 回答870 阅读
2 回答1.1k 阅读
1 回答643 阅读✓ 已解决
2 回答617 阅读
1 回答730 阅读
1 回答585 阅读
Java 代码
下面这个可能会快些,毕竟不需要执行完