int (Comparable<?> key1, Comparable<?> key2, boolean nullsLast) { if (key1 == null && key2 == null) return 0; if (key1 == null) return nullsLast ? 1 : -1; if (key2 == null) return nullsLast ? -1 : 1; if (key1 instanceof String && key2 instanceof String) { return naturalCompare((String)key1, (String)key2); } try { //noinspection unchecked,rawtypes return ((Comparable)key1).compareTo(key2); } catch (ClassCastException ignored) { // if custom nodes provide comparable keys of different types, // let's try to compare class names instead to avoid broken trees return key1.getClass().getName().compareTo(key2.getClass().getName()); } }