001package jmri.util;
002
003import java.util.Comparator;
004
005/**
006 * Perform an comparison using {@link AlphanumComparator}, followed up with a
007 * standard String comparison if
008 * {@link AlphanumComparator#compare(String, String)} returns 0.
009 * <p>
010 * If the requirement is that {@link Comparator#compare(Object, Object)} return
011 * 0 for two numerically identical Strings (i.e. {@code 42 == 0042}), use
012 * {@link AlphanumComparator}, but if the requirement is that Strings should be
013 * numerically ordered, but that non-identical representations should be
014 * different, (i.e. {@code 42 != 0042}, but order should be
015 * {@code 3, 4, 5, 42, 0042, 50}), use this Comparator, since the standard
016 * String comparator will not order numbers correctly.
017 *
018 * @author Randall Wood Copyright 2019
019 */
020public class PreferNumericComparator extends AlphanumComparator {
021
022    @Override
023    public int compare(String s1, String s2) {
024        int comparison;
025
026        try {
027            comparison = super.compare(s1, s2);
028        } catch (NumberFormatException e) {
029            comparison  = 0;  // ask for lexical compare
030        }
031        if (comparison == 0) {
032            return s1.compareTo(s2);
033        }
034        return comparison;
035    }
036}