是否有干净的语法来检查多个变量是否都具有相同的值?
我们有n个变量 X = {x1,x2,... xn}
它们不属于任何结构。
We have n variables X = {x1,x2,...xn}
they are not in any structures whatsoever.
在python中我可以这样做: if(x1 == x2 == x3 == xn):
In python for example I can do that: if (x1 == x2 == x3 == xn):
在java中我必须这样做: if((x1 == x2)&&(x2 == x3)&&(x3 == xn)):
In java I must do: if((x1 == x2) && (x2 == x3) && (x3 == xn)):
您是否知道改进此语法的简单方法? (想象一下很长的变量名和很多)
Do you know a simple way to improve this syntax? (Imagine very long variable name and lot of them)
谢谢。
如果你有很多这些变量,你是否考虑将它们放在一个集合中而不是将它们作为单独的变量?此时有各种选项。
If you have lots of these variables, have you considered putting them in a collection instead of having them as separate variables? There are various options at that point.
如果你发现自己做了很多,你可能想要编写辅助方法,可能使用varargs语法。例如:
If you find yourself doing this a lot, you might want to write helper methods, possibly using varargs syntax. For example:
public static boolean areAllEqual(int... values)
{
if (values.length == 0)
{
return true; // Alternative below
}
int checkValue = values[0];
for (int i = 1; i < values.length; i++)
{
if (values[i] != checkValue)
{
return false;
}
}
return true;
}
glowcoder提供的替代方案是强制至少有一个值:
An alternative as presented by glowcoder is to force there to be at least one value:
public static boolean areAllEqual(int checkValue, int... otherValues)
{
for (int value : otherValues)
{
if (value != checkValue)
{
return false;
}
}
return true;
}
在任何一种情况下,请使用:
In either case, use with:
if (HelperClass.areAllEqual(x1, x2, x3, x4, x5))
{
...
}