How to combine equality operators in an if statement in java? -
in python, can
if(a!=b!=c)
how can same thing in java without having separate them , write "&&" operators? i'm trying check 10 elements not equal, , don't want have write equality statement 45 times.
you cannot operation in java. note furthermore if a
, b
, etc., not primitives, should using equals
instead of ==
(or !=
). latter check object identity, not equality of values.
if want check whether 10 elements distinct, can throw them set
implementation (such hashset
) , check set contains 10 elements. or better (thanks @allonhadaya comment), check each element added. here's generic method works arbitrary number of objects of arbitrary type:
public static <t> boolean aredistinct(t... elements) { set<t> set = new hashset<t>(); (t element : elements) { if (!set.add(element)) { return false; } } return true; }
if elements primitives (e.g., int
), can write non-generic version specific type.
Comments
Post a Comment