001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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 */
017
018package org.apache.commons.lang3.compare;
019
020import java.io.Serializable;
021import java.util.Comparator;
022
023/**
024 * Compares Object's {@link Object#toString()} values.
025 *
026 * This class is stateless.
027 *
028 * @since 3.10
029 */
030public final class ObjectToStringComparator implements Comparator<Object>, Serializable {
031
032    /**
033     * Singleton instance.
034     *
035     * This class is stateless.
036     */
037    public static final ObjectToStringComparator INSTANCE = new ObjectToStringComparator();
038
039    /**
040     * For {@link Serializable}.
041     */
042    private static final long serialVersionUID = 1L;
043
044    @Override
045    public int compare(final Object o1, final Object o2) {
046        if (o1 == null && o2 == null) {
047            return 0;
048        }
049        if (o1 == null) {
050            return 1;
051        }
052        if (o2 == null) {
053            return -1;
054        }
055        final String string1 = o1.toString();
056        final String string2 = o2.toString();
057        // No guarantee that toString() returns a non-null value, despite what Spotbugs thinks.
058        if (string1 == null && string2 == null) {
059            return 0;
060        }
061        if (string1 == null) {
062            return 1;
063        }
064        if (string2 == null) {
065            return -1;
066        }
067        return string1.compareTo(string2);
068    }
069}