我有一个标志,我想传递给一个函数,该函数根据 map 中的值返回 true 或 false:
// userList is a List<String> and is stored as the value field in a map
// user is a String
if(flag)
{
if (userList == null)
return false;
else if(userList.size() == 0)
return true;
return userList.contains(user);
}
else
{
if (userList == null)
return true;
else if(userList.size() == 0)
return false;
return !userList.contains(user);
}
我的问题是:无论如何要整理这段代码,有很多复制(if 和 else 块是相同的,除了它们的返回值彼此相反)。
我不是一个非常有经验的代码,我真的很感激一些指导!
最佳答案
使用 flag
值而不是常量。
if (userList == null)
return !flag;
else if(userList.size() == 0)
return flag;
XOR
将用于最后一条语句(留给读者作为练习:-p)关于java - 返回值的反转,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18430711/