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    /**
045     * Constructs a new instance.
046     *
047     * @deprecated Will be private in 4.0.0.
048     */
049    @Deprecated
050    public ObjectToStringComparator() {
051        // empty
052    }
053
054    @Override
055    public int compare(final Object o1, final Object o2) {
056        if (o1 == null && o2 == null) {
057            return 0;
058        }
059        if (o1 == null) {
060            return 1;
061        }
062        if (o2 == null) {
063            return -1;
064        }
065        final String string1 = o1.toString();
066        final String string2 = o2.toString();
067        // No guarantee that toString() returns a non-null value, despite what Spotbugs thinks.
068        if (string1 == null && string2 == null) {
069            return 0;
070        }
071        if (string1 == null) {
072            return 1;
073        }
074        if (string2 == null) {
075            return -1;
076        }
077        return string1.compareTo(string2);
078    }
079}