001    /* 
002        Licensed to the Apache Software Foundation (ASF) under one
003        or more contributor license agreements.  See the NOTICE file
004        distributed with this work for additional information
005        regarding copyright ownership.  The ASF licenses this file
006        to you under the Apache License, Version 2.0 (the
007        "License"); you may not use this file except in compliance
008        with the License.  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,
013        software distributed under the License is distributed on an
014        "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015        KIND, either express or implied.  See the License for the
016        specific language governing permissions and limitations
017        under the License.  
018     */
019    
020    package org.apache.wiki.util.comparators;
021    
022    import java.util.Comparator;
023    
024    import org.apache.commons.lang.StringUtils;
025    
026    /**
027     * A comparator that sorts Strings using Java's "natural" order.
028     * 
029     */
030    public class JavaNaturalComparator implements Comparator<String>
031    {
032        // A special singleton instance for quick access
033        public static final Comparator<String> DEFAULT_JAVA_COMPARATOR = new JavaNaturalComparator();
034    
035        /*
036         * (non-Javadoc)
037         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
038         */
039        public int compare( String str1, String str2 ) {
040            if (StringUtils.equals( str1, str2 ) ) {
041                return 0; // the same object
042            }
043            if( str1 == null ) {
044                return -1; // str1 is null and str2 isn't so str1 is smaller
045            }
046            if( str2 == null ) {
047                return 1; // str2 is null and str1 isn't so str1 is bigger
048            }
049            return str1.compareTo( str2 );
050        }
051    }