Skip to content

Instantly share code, notes, and snippets.

@andreluisdias
Last active September 30, 2017 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreluisdias/d21bbd8b1ca4a8a7c696021908e68407 to your computer and use it in GitHub Desktop.
Save andreluisdias/d21bbd8b1ca4a8a7c696021908e68407 to your computer and use it in GitHub Desktop.
Generic Comparator Structure with Native assertions (example Integer)
package examples.algorithms;
import com.google.common.base.Stopwatch;
/**
* Generic Comparator with native assertions for Integers
*
* @author Andre Luis de Oliveira Dias (https://about.me/andreluisdias)
* @since 30 de set de 2017
*/
public class GenericComparator {
/**
* @param args
*/
public static void main(String[] args) {
GenericComparator tester = new GenericComparator();
/*
* Use JVM -ea hint to turn all below
*/
Stopwatch sw = Stopwatch.createStarted();
assert (tester.validateInteger(1, 1) == true);
assert (tester.validateInteger(1, 10) == false);
assert (tester.validateInteger(1, "") == false);
assert (tester.validateInteger(1, "1") == false);
assert (tester.validateInteger("", 1) == false);
assert (tester.validateInteger("", "") == false);
assert (tester.validateInteger("1", "1") == false);
sw.stop();
System.out.println(String.format("Total elapsed: %s", sw));
}
/*
* NULL-SAFE
*/
private boolean validateInteger(final Object i1, final Object i2) {
if (!this.validateClassAgainst(i1, i2, Integer.class)) return false; // Class validation
if (i1 == i2) return true; // Pointer validation
return (((Integer)i1).intValue() == ((Integer)i2).intValue()); // Specific implementation validation
}
private boolean validateClassAgainst(final Object o1, final Object o2, final Class<?> clazz) {
if (o1 == null) return false;
if (o2 == null) return false;
if (
!o1.getClass().equals(clazz)
||
!o2.getClass().equals(clazz)
){
return false;
}
return true;
}
}
@andreluisdias
Copy link
Author

StopWatch added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment