001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2012 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * Sonar is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.duplications.utils;
021    
022    import java.util.Comparator;
023    
024    /**
025     * More efficient (in terms of performance) implementation of a String comparator.
026     * Speed is gained by using hash code as a primary comparison attribute, which is cached for String.
027     * Be aware that this ordering is not lexicographic, however stable.
028     */
029    public final class FastStringComparator implements Comparator<String> {
030    
031      public static final FastStringComparator INSTANCE = new FastStringComparator();
032    
033      /**
034       * Compares two strings (not lexicographically).
035       */
036      public int compare(String s1, String s2) {
037        if (s1 == s2) { // NOSONAR false-positive: Compare Objects With Equals
038          return 0;
039        }
040        int h1 = s1.hashCode();
041        int h2 = s2.hashCode();
042        if (h1 < h2) {
043          return -1;
044        } else if (h1 > h2) {
045          return 1;
046        } else {
047          return s1.compareTo(s2);
048        }
049      }
050    
051      /**
052       * Enforce use of a singleton instance.
053       */
054      private FastStringComparator() {
055      }
056    
057    }