001/*-------------------------------------------------------------------------+
002|                                                                          |
003| Copyright 2005-2011 The ConQAT Project                                   |
004|                                                                          |
005| Licensed under the Apache License, Version 2.0 (the "License");          |
006| you may not use this file except in compliance with the License.         |
007| You may obtain a copy of the License at                                  |
008|                                                                          |
009|    http://www.apache.org/licenses/LICENSE-2.0                            |
010|                                                                          |
011| Unless required by applicable law or agreed to in writing, software      |
012| distributed under the License is distributed on an "AS IS" BASIS,        |
013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
014| See the License for the specific language governing permissions and      |
015| limitations under the License.                                           |
016+-------------------------------------------------------------------------*/
017package org.conqat.lib.commons.string;
018
019import java.util.Comparator;
020
021/**
022 * This is a more efficient implementation of a String comparator. While the
023 * comparison order is stable, there is no guarantee that is is lexicographic.
024 * The additional speed is gained by using the hash code as primary comparison
025 * attribute. As the hash code is cached by the string object, its access is
026 * very cheap even for long strings.
027 * 
028 * @author hummelb
029 */
030public class FastStringComparator implements Comparator<String> {
031
032        /** Singleton instance. */
033        public static final FastStringComparator INSTANCE = new FastStringComparator();
034
035        /** {@inheritDoc} */
036        @Override
037        public int compare(String s0, String s1) {
038                if (s0 == s1) {
039                        return 0;
040                }
041                int hash0 = s0.hashCode();
042                int hash1 = s1.hashCode();
043                if (hash0 < hash1) {
044                        return -1;
045                }
046                if (hash0 > hash1) {
047                        return 1;
048                }
049
050                return s0.compareTo(s1);
051        }
052}