Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

java - Is there clean syntax for checking if multiple variables all have the same value?

We have n variables X = {x1,x2,...xn} they are not in any structures whatsoever.

In python for example I can do that: if (x1 == x2 == 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)

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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;
}

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))
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...