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