Check two arguments for zero in elegant style

I repeat the two collections and check if both collections contain the same elements . I can not use Java 8.

Both collections contain elements that are comparable , and the content is defined as equal if all elements return a x.compareTo(y) with 0.

Two values ​​are defined as different if one of them is zero, but not the other . I want to find an elegant way to compare by invalidity and prevent a zero check of the final compareTo() .

My current implementation:

  public static <T extends Comparable<T>> boolean isSame(@Nullable Collection<T> a, @Nullable Collection<T> b) { if (a == null || b == null) { return (a == null && b == null); } if (a.size() != b.size()) { return false; } Iterator<T> aIt = a.iterator(); Iterator<T> bIt = b.iterator(); while (aIt.hasNext()) { T aValue = aIt.next(); T bValue = bIt.next(); if (aValue == null || bValue == null) { if (aValue == null ^ bValue == null) { return false; } //both null, don't compare, continue looping... } else if (aValue.compareTo(bValue) != 0) { return false; } } return true; } 

I want to continue the while loop if both values ​​are zero, as this is defined as equal.

But I'm struggling with this part:

 if (aValue == null || bValue == null) { if (aValue == null ^ bValue == null) { return false; } } 

Question:

Is there a more elegant and readable way to compare for invalidity, do an additional comparison if both values ​​are non-zero, return false if only one of them is zero, and continue the cycle if both values ​​are zero?

+5
source share
2 answers

The sequence below should work well:

 if(aValue == null && bValue == null) continue; // both null; continue if(aValue == null || bValue == null) return false; // any null; return false if(aValue.compareTo(bValue) != 0) { // both non-null; compare return false; } 
+6
source

In Java8, you can create a Comparator that replaces the comparison sequence for the cost of creating an additional object (you will need to decide whether you care about this):

 Comparator<T> cmp = Comparator.nullsLast(Comparator.naturalOrder()); 

The comparer will take care of the null comparison for you (since you think the two null are equal):

 while (aIt.hasNext()) { T aValue = aIt.next(); T bValue = bIt.next(); if (cmp.compare(aValue, bValue) != 0) { return false; } } 
+3
source

Source: https://habr.com/ru/post/1271290/


All Articles