    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 */
    017package org.apache.commons.lang3;
    018
    019import java.io.IOException;
    020import java.io.Serializable;
    021import java.lang.reflect.Array;
    022import java.lang.reflect.InvocationTargetException;
    023import java.lang.reflect.Method;
    024import java.util.Collections;
    025import java.util.Comparator;
    026import java.util.HashMap;
    027import java.util.Map;
    028import java.util.TreeSet;
    029
    030import org.apache.commons.lang3.exception.CloneFailedException;
    031import org.apache.commons.lang3.mutable.MutableInt;
    032import org.apache.commons.lang3.text.StrBuilder;
    033
    034/**
    035 * <p>Operations on {@code Object}.</p>
    036 *
    037 * <p>This class tries to handle {@code null} input gracefully.
    038 * An exception will generally not be thrown for a {@code null} input.
    039 * Each method documents its behaviour in more detail.</p>
    040 *
    041 * <p>#ThreadSafe#</p>
    042 * @since 1.0
    043 */
    044//@Immutable
    045@SuppressWarnings("deprecation") // deprecated class StrBuilder is imported
    046// because it is part of the signature of deprecated methods
    047public class ObjectUtils {
    048
    049    private static final char AT_SIGN = '@';
    050
    051    /**
    052     * <p>Singleton used as a {@code null} placeholder where
    053     * {@code null} has another meaning.</p>
    054     *
    055     * <p>For example, in a {@code HashMap} the
    056     * {@link java.util.HashMap#get(java.lang.Object)} method returns
    057     * {@code null} if the {@code Map} contains {@code null} or if there
    058     * is no matching key. The {@code Null} placeholder can be used to
    059     * distinguish between these two cases.</p>
    060     *
    061     * <p>Another example is {@code Hashtable}, where {@code null}
    062     * cannot be stored.</p>
    063     *
    064     * <p>This instance is Serializable.</p>
    065     */
    066    public static final Null NULL = new Null();
    067
    068    /**
    069     * <p>{@code ObjectUtils} instances should NOT be constructed in
    070     * standard programming. Instead, the static methods on the class should
    071     * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.</p>
    072     *
    073     * <p>This constructor is public to permit tools that require a JavaBean
    074     * instance to operate.</p>
    075     */
    076    public ObjectUtils() {
    077        super();
    078    }
    079
    080    // Defaulting
    081    //-----------------------------------------------------------------------
    082    /**
    083     * <p>Returns a default value if the object passed is {@code null}.</p>
    084     *
    085     * <pre>
    086     * ObjectUtils.defaultIfNull(null, null)      = null
    087     * ObjectUtils.defaultIfNull(null, "")        = ""
    088     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
    089     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
    090     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
    091     * </pre>
    092     *
    093     * @param <T> the type of the object
    094     * @param object  the {@code Object} to test, may be {@code null}
    095     * @param defaultValue  the default value to return, may be {@code null}
    096     * @return {@code object} if it is not {@code null}, defaultValue otherwise
    097     */
    098    public static <T> T defaultIfNull(final T object, final T defaultValue) {
    099        return object != null ? object : defaultValue;
    100    }
    101
    102    /**
    103     * <p>Returns the first value in the array which is not {@code null}.
    104     * If all the values are {@code null} or the array is {@code null}
    105     * or empty then {@code null} is returned.</p>
    106     *
    107     * <pre>
    108     * ObjectUtils.firstNonNull(null, null)      = null
    109     * ObjectUtils.firstNonNull(null, "")        = ""
    110     * ObjectUtils.firstNonNull(null, null, "")  = ""
    111     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
    112     * ObjectUtils.firstNonNull("abc", *)        = "abc"
    113     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
    114     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
    115     * ObjectUtils.firstNonNull()                = null
    116     * </pre>
    117     *
    118     * @param <T> the component type of the array
    119     * @param values  the values to test, may be {@code null} or empty
    120     * @return the first value from {@code values} which is not {@code null},
    121     *  or {@code null} if there are no non-null values
    122     * @since 3.0
    123     */
    124    @SafeVarargs
    125    public static <T> T firstNonNull(final T... values) {
    126        if (values != null) {
    127            for (final T val : values) {
    128                if (val != null) {
    129                    return val;
    130                }
    131            }
    132        }
    133        return null;
    134    }
    135
    136    /**
    137     * Checks if any value in the given array is not {@code null}.
    138     *
    139     * <p>
    140     * If all the values are {@code null} or the array is {@code null}
    141     * or empty then {@code false} is returned. Otherwise {@code true} is returned.
    142     * </p>
    143     *
    144     * <pre>
    145     * ObjectUtils.anyNotNull(*)                = true
    146     * ObjectUtils.anyNotNull(*, null)          = true
    147     * ObjectUtils.anyNotNull(null, *)          = true
    148     * ObjectUtils.anyNotNull(null, null, *, *) = true
    149     * ObjectUtils.anyNotNull(null)             = false
    150     * ObjectUtils.anyNotNull(null, null)       = false
    151     * </pre>
    152     *
    153     * @param values  the values to test, may be {@code null} or empty
    154     * @return {@code true} if there is at least one non-null value in the array,
    155     * {@code false} if all values in the array are {@code null}s.
    156     * If the array is {@code null} or empty {@code false} is also returned.
    157     * @since 3.5
    158     */
    159    public static boolean anyNotNull(final Object... values) {
    160        return firstNonNull(values) != null;
    161    }
    162
    163    /**
    164     * Checks if all values in the array are not {@code nulls}.
    165     *
    166     * <p>
    167     * If any value is {@code null} or the array is {@code null} then
    168     * {@code false} is returned. If all elements in array are not
    169     * {@code null} or the array is empty (contains no elements) {@code true}
    170     * is returned.
    171     * </p>
    172     *
    173     * <pre>
    174     * ObjectUtils.allNotNull(*)             = true
    175     * ObjectUtils.allNotNull(*, *)          = true
    176     * ObjectUtils.allNotNull(null)          = false
    177     * ObjectUtils.allNotNull(null, null)    = false
    178     * ObjectUtils.allNotNull(null, *)       = false
    179     * ObjectUtils.allNotNull(*, null)       = false
    180     * ObjectUtils.allNotNull(*, *, null, *) = false
    181     * </pre>
    182     *
    183     * @param values  the values to test, may be {@code null} or empty
    184     * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null},
    185     * {@code true} if all values in the array are not {@code null}s or array contains no elements.
    186     * @since 3.5
    187     */
    188    public static boolean allNotNull(final Object... values) {
    189        if (values == null) {
    190            return false;
    191        }
    192
    193        for (final Object val : values) {
    194            if (val == null) {
    195                return false;
    196            }
    197        }
    198
    199        return true;
    200    }
    201
    202    // Null-safe equals/hashCode
    203    //-----------------------------------------------------------------------
    204    /**
    205     * <p>Compares two objects for equality, where either one or both
    206     * objects may be {@code null}.</p>
    207     *
    208     * <pre>
    209     * ObjectUtils.equals(null, null)                  = true
    210     * ObjectUtils.equals(null, "")                    = false
    211     * ObjectUtils.equals("", null)                    = false
    212     * ObjectUtils.equals("", "")                      = true
    213     * ObjectUtils.equals(Boolean.TRUE, null)          = false
    214     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
    215     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
    216     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
    217     * </pre>
    218     *
    219     * @param object1  the first object, may be {@code null}
    220     * @param object2  the second object, may be {@code null}
    221     * @return {@code true} if the values of both objects are the same
    222     * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will
    223     * be removed from future releases.
    224     */
    225    @Deprecated
    226    public static boolean equals(final Object object1, final Object object2) {
    227        if (object1 == object2) {
    228            return true;
    229        }
    230        if (object1 == null || object2 == null) {
    231            return false;
    232        }
    233        return object1.equals(object2);
    234    }
    235
    236    /**
    237     * <p>Compares two objects for inequality, where either one or both
    238     * objects may be {@code null}.</p>
    239     *
    240     * <pre>
    241     * ObjectUtils.notEqual(null, null)                  = false
    242     * ObjectUtils.notEqual(null, "")                    = true
    243     * ObjectUtils.notEqual("", null)                    = true
    244     * ObjectUtils.notEqual("", "")                      = false
    245     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
    246     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
    247     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
    248     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
    249     * </pre>
    250     *
    251     * @param object1  the first object, may be {@code null}
    252     * @param object2  the second object, may be {@code null}
    253     * @return {@code false} if the values of both objects are the same
    254     */
    255    public static boolean notEqual(final Object object1, final Object object2) {
    256        return !equals(object1, object2);
    257    }
    258
    259    /**
    260     * <p>Gets the hash code of an object returning zero when the
    261     * object is {@code null}.</p>
    262     *
    263     * <pre>
    264     * ObjectUtils.hashCode(null)   = 0
    265     * ObjectUtils.hashCode(obj)    = obj.hashCode()
    266     * </pre>
    267     *
    268     * @param obj  the object to obtain the hash code of, may be {@code null}
    269     * @return the hash code of the object, or zero if null
    270     * @since 2.1
    271     * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be
    272     * removed in future releases
    273     */
    274    @Deprecated
    275    public static int hashCode(final Object obj) {
    276        // hashCode(Object) retained for performance, as hash code is often critical
    277        return obj == null ? 0 : obj.hashCode();
    278    }
    279
    280    /**
    281     * <p>Gets the hash code for multiple objects.</p>
    282     *
    283     * <p>This allows a hash code to be rapidly calculated for a number of objects.
    284     * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
    285     * The hash code for multiple objects is the same as that calculated by an
    286     * {@code ArrayList} containing the specified objects.</p>
    287     *
    288     * <pre>
    289     * ObjectUtils.hashCodeMulti()                 = 1
    290     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
    291     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
    292     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
    293     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
    294     * </pre>
    295     *
    296     * @param objects  the objects to obtain the hash code of, may be {@code null}
    297     * @return the hash code of the objects, or zero if null
    298     * @since 3.0
    299     * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be
    300     * removed in future releases.
    301     */
    302    @Deprecated
    303    public static int hashCodeMulti(final Object... objects) {
    304        int hash = 1;
    305        if (objects != null) {
    306            for (final Object object : objects) {
    307                final int tmpHash = hashCode(object);
    308                hash = hash * 31 + tmpHash;
    309            }
    310        }
    311        return hash;
    312    }
    313
    314    // Identity ToString
    315    //-----------------------------------------------------------------------
    316    /**
    317     * <p>Gets the toString that would be produced by {@code Object}
    318     * if a class did not override toString itself. {@code null}
    319     * will return {@code null}.</p>
    320     *
    321     * <pre>
    322     * ObjectUtils.identityToString(null)         = null
    323     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
    324     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
    325     * </pre>
    326     *
    327     * @param object  the object to create a toString for, may be
    328     *  {@code null}
    329     * @return the default toString text, or {@code null} if
    330     *  {@code null} passed in
    331     */
    332    public static String identityToString(final Object object) {
    333        if (object == null) {
    334            return null;
    335        }
    336        final String name = object.getClass().getName();
    337        final String hexString = Integer.toHexString(System.identityHashCode(object));
    338        final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length());
    339        // @formatter:off
    340        builder.append(name)
    341              .append(AT_SIGN)
    342              .append(hexString);
    343        // @formatter:off
    344        return builder.toString();
    345    }
    346
    347    /**
    348     * <p>Appends the toString that would be produced by {@code Object}
    349     * if a class did not override toString itself. {@code null}
    350     * will throw a NullPointerException for either of the two parameters. </p>
    351     *
    352     * <pre>
    353     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
    354     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
    355     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
    356     * </pre>
    357     *
    358     * @param appendable  the appendable to append to
    359     * @param object  the object to create a toString for
    360     * @throws IOException if an I/O error occurs
    361     * @since 3.2
    362     */
    363    public static void identityToString(final Appendable appendable, final Object object) throws IOException {
    364        Validate.notNull(object, "Cannot get the toString of a null object");
    365        appendable.append(object.getClass().getName())
    366              .append(AT_SIGN)
    367              .append(Integer.toHexString(System.identityHashCode(object)));
    368    }
    369
    370    /**
    371     * <p>Appends the toString that would be produced by {@code Object}
    372     * if a class did not override toString itself. {@code null}
    373     * will throw a NullPointerException for either of the two parameters. </p>
    374     *
    375     * <pre>
    376     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
    377     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
    378     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    379     * </pre>
    380     *
    381     * @param builder  the builder to append to
    382     * @param object  the object to create a toString for
    383     * @since 3.2
    384     * @deprecated as of 3.6, because StrBuilder was moved to commons-text,
    385     *  use one of the other {@code identityToString} methods instead
    386     */
    387    @Deprecated
    388    public static void identityToString(final StrBuilder builder, final Object object) {
    389        Validate.notNull(object, "Cannot get the toString of a null object");
    390        final String name = object.getClass().getName();
    391        final String hexString = Integer.toHexString(System.identityHashCode(object));
    392        builder.ensureCapacity(builder.length() +  name.length() + 1 + hexString.length());
    393        builder.append(name)
    394              .append(AT_SIGN)
    395              .append(hexString);
    396    }
    397
    398    /**
    399     * <p>Appends the toString that would be produced by {@code Object}
    400     * if a class did not override toString itself. {@code null}
    401     * will throw a NullPointerException for either of the two parameters. </p>
    402     *
    403     * <pre>
    404     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
    405     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
    406     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
    407     * </pre>
    408     *
    409     * @param buffer  the buffer to append to
    410     * @param object  the object to create a toString for
    411     * @since 2.4
    412     */
    413    public static void identityToString(final StringBuffer buffer, final Object object) {
    414        Validate.notNull(object, "Cannot get the toString of a null object");
    415        final String name = object.getClass().getName();
    416        final String hexString = Integer.toHexString(System.identityHashCode(object));
    417        buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length());
    418        buffer.append(name)
    419              .append(AT_SIGN)
    420              .append(hexString);
    421    }
    422
    423    /**
    424     * <p>Appends the toString that would be produced by {@code Object}
    425     * if a class did not override toString itself. {@code null}
    426     * will throw a NullPointerException for either of the two parameters. </p>
    427     *
    428     * <pre>
    429     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
    430     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
    431     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    432     * </pre>
    433     *
    434     * @param builder  the builder to append to
    435     * @param object  the object to create a toString for
    436     * @since 3.2
    437     */
    438    public static void identityToString(final StringBuilder builder, final Object object) {
    439        Validate.notNull(object, "Cannot get the toString of a null object");
    440        final String name = object.getClass().getName();
    441        final String hexString = Integer.toHexString(System.identityHashCode(object));
    442        builder.ensureCapacity(builder.length() +  name.length() + 1 + hexString.length());
    443        builder.append(name)
    444              .append(AT_SIGN)
    445              .append(hexString);
    446    }
    447
    448    // ToString
    449    //-----------------------------------------------------------------------
    450    /**
    451     * <p>Gets the {@code toString} of an {@code Object} returning
    452     * an empty string ("") if {@code null} input.</p>
    453     *
    454     * <pre>
    455     * ObjectUtils.toString(null)         = ""
    456     * ObjectUtils.toString("")           = ""
    457     * ObjectUtils.toString("bat")        = "bat"
    458     * ObjectUtils.toString(Boolean.TRUE) = "true"
    459     * </pre>
    460     *
    461     * @see StringUtils#defaultString(String)
    462     * @see String#valueOf(Object)
    463     * @param obj  the Object to {@code toString}, may be null
    464     * @return the passed in Object's toString, or {@code ""} if {@code null} input
    465     * @since 2.0
    466     * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be
    467     * removed in future releases. Note however that said method will return "null" for null references, while this
    468     * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")}
    469     */
    470    @Deprecated
    471    public static String toString(final Object obj) {
    472        return obj == null ? StringUtils.EMPTY : obj.toString();
    473    }
    474
    475    /**
    476     * <p>Gets the {@code toString} of an {@code Object} returning
    477     * a specified text if {@code null} input.</p>
    478     *
    479     * <pre>
    480     * ObjectUtils.toString(null, null)           = null
    481     * ObjectUtils.toString(null, "null")         = "null"
    482     * ObjectUtils.toString("", "null")           = ""
    483     * ObjectUtils.toString("bat", "null")        = "bat"
    484     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
    485     * </pre>
    486     *
    487     * @see StringUtils#defaultString(String,String)
    488     * @see String#valueOf(Object)
    489     * @param obj  the Object to {@code toString}, may be null
    490     * @param nullStr  the String to return if {@code null} input, may be null
    491     * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
    492     * @since 2.0
    493     * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and
    494     * will be removed in future releases.
    495     */
    496    @Deprecated
    497    public static String toString(final Object obj, final String nullStr) {
    498        return obj == null ? nullStr : obj.toString();
    499    }
    500
    501    // Comparable
    502    //-----------------------------------------------------------------------
    503    /**
    504     * <p>Null safe comparison of Comparables.</p>
    505     *
    506     * @param <T> type of the values processed by this method
    507     * @param values the set of comparable values, may be null
    508     * @return
    509     *  <ul>
    510     *   <li>If any objects are non-null and unequal, the lesser object.
    511     *   <li>If all objects are non-null and equal, the first.
    512     *   <li>If any of the comparables are null, the lesser of the non-null objects.
    513     *   <li>If all the comparables are null, null is returned.
    514     *  </ul>
    515     */
    516    @SafeVarargs
    517    public static <T extends Comparable<? super T>> T min(final T... values) {
    518        T result = null;
    519        if (values != null) {
    520            for (final T value : values) {
    521                if (compare(value, result, true) < 0) {
    522                    result = value;
    523                }
    524            }
    525        }
    526        return result;
    527    }
    528
    529    /**
    530     * <p>Null safe comparison of Comparables.</p>
    531     *
    532     * @param <T> type of the values processed by this method
    533     * @param values the set of comparable values, may be null
    534     * @return
    535     *  <ul>
    536     *   <li>If any objects are non-null and unequal, the greater object.
    537     *   <li>If all objects are non-null and equal, the first.
    538     *   <li>If any of the comparables are null, the greater of the non-null objects.
    539     *   <li>If all the comparables are null, null is returned.
    540     *  </ul>
    541     */
    542    @SafeVarargs
    543    public static <T extends Comparable<? super T>> T max(final T... values) {
    544        T result = null;
    545        if (values != null) {
    546            for (final T value : values) {
    547                if (compare(value, result, false) > 0) {
    548                    result = value;
    549                }
    550            }
    551        }
    552        return result;
    553    }
    554
    555    /**
    556     * <p>Null safe comparison of Comparables.
    557     * {@code null} is assumed to be less than a non-{@code null} value.</p>
    558     *
    559     * @param <T> type of the values processed by this method
    560     * @param c1  the first comparable, may be null
    561     * @param c2  the second comparable, may be null
    562     * @return a negative value if c1 &lt; c2, zero if c1 = c2
    563     *  and a positive value if c1 &gt; c2
    564     */
    565    public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) {
    566        return compare(c1, c2, false);
    567    }
    568
    569    /**
    570     * <p>Null safe comparison of Comparables.</p>
    571     *
    572     * @param <T> type of the values processed by this method
    573     * @param c1  the first comparable, may be null
    574     * @param c2  the second comparable, may be null
    575     * @param nullGreater if true {@code null} is considered greater
    576     *  than a non-{@code null} value or if false {@code null} is
    577     *  considered less than a Non-{@code null} value
    578     * @return a negative value if c1 &lt; c2, zero if c1 = c2
    579     *  and a positive value if c1 &gt; c2
    580     * @see java.util.Comparator#compare(Object, Object)
    581     */
    582    public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
    583        if (c1 == c2) {
    584            return 0;
    585        } else if (c1 == null) {
    586            return nullGreater ? 1 : -1;
    587        } else if (c2 == null) {
    588            return nullGreater ? -1 : 1;
    589        }
    590        return c1.compareTo(c2);
    591    }
    592
    593    /**
    594     * Find the "best guess" middle value among comparables. If there is an even
    595     * number of total values, the lower of the two middle values will be returned.
    596     * @param <T> type of values processed by this method
    597     * @param items to compare
    598     * @return T at middle position
    599     * @throws NullPointerException if items is {@code null}
    600     * @throws IllegalArgumentException if items is empty or contains {@code null} values
    601     * @since 3.0.1
    602     */
    603    @SafeVarargs
    604    public static <T extends Comparable<? super T>> T median(final T... items) {
    605        Validate.notEmpty(items);
    606        Validate.noNullElements(items);
    607        final TreeSet<T> sort = new TreeSet<>();
    608        Collections.addAll(sort, items);
    609        @SuppressWarnings("unchecked") //we know all items added were T instances
    610        final T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    611        return result;
    612    }
    613
    614    /**
    615     * Find the "best guess" middle value among comparables. If there is an even
    616     * number of total values, the lower of the two middle values will be returned.
    617     * @param <T> type of values processed by this method
    618     * @param comparator to use for comparisons
    619     * @param items to compare
    620     * @return T at middle position
    621     * @throws NullPointerException if items or comparator is {@code null}
    622     * @throws IllegalArgumentException if items is empty or contains {@code null} values
    623     * @since 3.0.1
    624     */
    625    @SafeVarargs
    626    public static <T> T median(final Comparator<T> comparator, final T... items) {
    627        Validate.notEmpty(items, "null/empty items");
    628        Validate.noNullElements(items);
    629        Validate.notNull(comparator, "null comparator");
    630        final TreeSet<T> sort = new TreeSet<>(comparator);
    631        Collections.addAll(sort, items);
    632        @SuppressWarnings("unchecked") //we know all items added were T instances
    633        final
    634        T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    635        return result;
    636    }
    637
    638    // Mode
    639    //-----------------------------------------------------------------------
    640    /**
    641     * Find the most frequently occurring item.
    642     *
    643     * @param <T> type of values processed by this method
    644     * @param items to check
    645     * @return most populous T, {@code null} if non-unique or no items supplied
    646     * @since 3.0.1
    647     */
    648    @SafeVarargs
    649    public static <T> T mode(final T... items) {
    650        if (ArrayUtils.isNotEmpty(items)) {
    651            final HashMap<T, MutableInt> occurrences = new HashMap<>(items.length);
    652            for (final T t : items) {
    653                final MutableInt count = occurrences.get(t);
    654                if (count == null) {
    655                    occurrences.put(t, new MutableInt(1));
    656                } else {
    657                    count.increment();
    658                }
    659            }
    660            T result = null;
    661            int max = 0;
    662            for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
    663                final int cmp = e.getValue().intValue();
    664                if (cmp == max) {
    665                    result = null;
    666                } else if (cmp > max) {
    667                    max = cmp;
    668                    result = e.getKey();
    669                }
    670            }
    671            return result;
    672        }
    673        return null;
    674    }
    675
    676    // cloning
    677    //-----------------------------------------------------------------------
    678    /**
    679     * <p>Clone an object.</p>
    680     *
    681     * @param <T> the type of the object
    682     * @param obj  the object to clone, null returns null
    683     * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
    684     * @throws CloneFailedException if the object is cloneable and the clone operation fails
    685     * @since 3.0
    686     */
    687    public static <T> T clone(final T obj) {
    688        if (obj instanceof Cloneable) {
    689            final Object result;
    690            if (obj.getClass().isArray()) {
    691                final Class<?> componentType = obj.getClass().getComponentType();
    692                if (componentType.isPrimitive()) {
    693                    int length = Array.getLength(obj);
    694                    result = Array.newInstance(componentType, length);
    695                    while (length-- > 0) {
    696                        Array.set(result, length, Array.get(obj, length));
    697                    }
    698                } else {
    699                    result = ((Object[]) obj).clone();
    700                }
    701            } else {
    702                try {
    703                    final Method clone = obj.getClass().getMethod("clone");
    704                    result = clone.invoke(obj);
    705                } catch (final NoSuchMethodException e) {
    706                    throw new CloneFailedException("Cloneable type "
    707                        + obj.getClass().getName()
    708                        + " has no clone method", e);
    709                } catch (final IllegalAccessException e) {
    710                    throw new CloneFailedException("Cannot clone Cloneable type "
    711                        + obj.getClass().getName(), e);
    712                } catch (final InvocationTargetException e) {
    713                    throw new CloneFailedException("Exception cloning Cloneable type "
    714                        + obj.getClass().getName(), e.getCause());
    715                }
    716            }
    717            @SuppressWarnings("unchecked") // OK because input is of type T
    718            final T checked = (T) result;
    719            return checked;
    720        }
    721
    722        return null;
    723    }
    724
    725    /**
    726     * <p>Clone an object if possible.</p>
    727     *
    728     * <p>This method is similar to {@link #clone(Object)}, but will return the provided
    729     * instance as the return value instead of {@code null} if the instance
    730     * is not cloneable. This is more convenient if the caller uses different
    731     * implementations (e.g. of a service) and some of the implementations do not allow concurrent
    732     * processing or have state. In such cases the implementation can simply provide a proper
    733     * clone implementation and the caller's code does not have to change.</p>
    734     *
    735     * @param <T> the type of the object
    736     * @param obj  the object to clone, null returns null
    737     * @return the clone if the object implements {@link Cloneable} otherwise the object itself
    738     * @throws CloneFailedException if the object is cloneable and the clone operation fails
    739     * @since 3.0
    740     */
    741    public static <T> T cloneIfPossible(final T obj) {
    742        final T clone = clone(obj);
    743        return clone == null ? obj : clone;
    744    }
    745
    746    // Null
    747    //-----------------------------------------------------------------------
    748    /**
    749     * <p>Class used as a null placeholder where {@code null}
    750     * has another meaning.</p>
    751     *
    752     * <p>For example, in a {@code HashMap} the
    753     * {@link java.util.HashMap#get(java.lang.Object)} method returns
    754     * {@code null} if the {@code Map} contains {@code null} or if there is
    755     * no matching key. The {@code Null} placeholder can be used to distinguish
    756     * between these two cases.</p>
    757     *
    758     * <p>Another example is {@code Hashtable}, where {@code null}
    759     * cannot be stored.</p>
    760     */
    761    public static class Null implements Serializable {
    762        /**
    763         * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
    764         *
    765         * @see java.io.Serializable
    766         */
    767        private static final long serialVersionUID = 7092611880189329093L;
    768
    769        /**
    770         * Restricted constructor - singleton.
    771         */
    772        Null() {
    773            super();
    774        }
    775
    776        /**
    777         * <p>Ensure singleton.</p>
    778         *
    779         * @return the singleton value
    780         */
    781        private Object readResolve() {
    782            return NULL;
    783        }
    784    }
    785
    786
    787    // Constants (LANG-816):
    788    /*
    789        These methods ensure constants are not inlined by javac.
    790        For example, typically a developer might declare a constant like so:
    791
    792            public final static int MAGIC_NUMBER = 5;
    793
    794        Should a different jar file refer to this, and the MAGIC_NUMBER
    795        is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar
    796        file will need to recompile itself.  This is because javac
    797        typically inlines the primitive or String constant directly into
    798        the bytecode, and removes the reference to the MAGIC_NUMBER field.
    799
    800        To help the other jar (so that it does not need to recompile
    801        when constants are changed) the original developer can declare
    802        their constant using one of the CONST() utility methods, instead:
    803
    804            public final static int MAGIC_NUMBER = CONST(5);
    805     */
    806
    807
    808    /**
    809     * This method returns the provided value unchanged.
    810     * This can prevent javac from inlining a constant
    811     * field, e.g.,
    812     *
    813     * <pre>
    814     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
    815     * </pre>
    816     *
    817     * This way any jars that refer to this field do not
    818     * have to recompile themselves if the field's value
    819     * changes at some future date.
    820     *
    821     * @param v the boolean value to return
    822     * @return the boolean v, unchanged
    823     * @since 3.2
    824     */
    825    public static boolean CONST(final boolean v) {
    826        return v;
    827    }
    828
    829    /**
    830     * This method returns the provided value unchanged.
    831     * This can prevent javac from inlining a constant
    832     * field, e.g.,
    833     *
    834     * <pre>
    835     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
    836     * </pre>
    837     *
    838     * This way any jars that refer to this field do not
    839     * have to recompile themselves if the field's value
    840     * changes at some future date.
    841     *
    842     * @param v the byte value to return
    843     * @return the byte v, unchanged
    844     * @since 3.2
    845     */
    846    public static byte CONST(final byte v) {
    847        return v;
    848    }
    849
    850    /**
    851     * This method returns the provided value unchanged.
    852     * This can prevent javac from inlining a constant
    853     * field, e.g.,
    854     *
    855     * <pre>
    856     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
    857     * </pre>
    858     *
    859     * This way any jars that refer to this field do not
    860     * have to recompile themselves if the field's value
    861     * changes at some future date.
    862     *
    863     * @param v the byte literal (as an int) value to return
    864     * @throws IllegalArgumentException if the value passed to v
    865     *         is larger than a byte, that is, smaller than -128 or
    866     *         larger than 127.
    867     * @return the byte v, unchanged
    868     * @since 3.2
    869     */
    870    public static byte CONST_BYTE(final int v) {
    871        if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) {
    872            throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]");
    873        }
    874        return (byte) v;
    875    }
    876
    877    /**
    878     * This method returns the provided value unchanged.
    879     * This can prevent javac from inlining a constant
    880     * field, e.g.,
    881     *
    882     * <pre>
    883     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
    884     * </pre>
    885     *
    886     * This way any jars that refer to this field do not
    887     * have to recompile themselves if the field's value
    888     * changes at some future date.
    889     *
    890     * @param v the char value to return
    891     * @return the char v, unchanged
    892     * @since 3.2
    893     */
    894    public static char CONST(final char v) {
    895        return v;
    896    }
    897
    898    /**
    899     * This method returns the provided value unchanged.
    900     * This can prevent javac from inlining a constant
    901     * field, e.g.,
    902     *
    903     * <pre>
    904     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
    905     * </pre>
    906     *
    907     * This way any jars that refer to this field do not
    908     * have to recompile themselves if the field's value
    909     * changes at some future date.
    910     *
    911     * @param v the short value to return
    912     * @return the short v, unchanged
    913     * @since 3.2
    914     */
    915    public static short CONST(final short v) {
    916        return v;
    917    }
    918
    919    /**
    920     * This method returns the provided value unchanged.
    921     * This can prevent javac from inlining a constant
    922     * field, e.g.,
    923     *
    924     * <pre>
    925     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
    926     * </pre>
    927     *
    928     * This way any jars that refer to this field do not
    929     * have to recompile themselves if the field's value
    930     * changes at some future date.
    931     *
    932     * @param v the short literal (as an int) value to return
    933     * @throws IllegalArgumentException if the value passed to v
    934     *         is larger than a short, that is, smaller than -32768 or
    935     *         larger than 32767.
    936     * @return the byte v, unchanged
    937     * @since 3.2
    938     */
    939    public static short CONST_SHORT(final int v) {
    940        if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) {
    941            throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]");
    942        }
    943        return (short) v;
    944    }
    945
    946
    947    /**
    948     * This method returns the provided value unchanged.
    949     * This can prevent javac from inlining a constant
    950     * field, e.g.,
    951     *
    952     * <pre>
    953     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
    954     * </pre>
    955     *
    956     * This way any jars that refer to this field do not
    957     * have to recompile themselves if the field's value
    958     * changes at some future date.
    959     *
    960     * @param v the int value to return
    961     * @return the int v, unchanged
    962     * @since 3.2
    963     */
    964    public static int CONST(final int v) {
    965        return v;
    966    }
    967
    968    /**
    969     * This method returns the provided value unchanged.
    970     * This can prevent javac from inlining a constant
    971     * field, e.g.,
    972     *
    973     * <pre>
    974     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
    975     * </pre>
    976     *
    977     * This way any jars that refer to this field do not
    978     * have to recompile themselves if the field's value
    979     * changes at some future date.
    980     *
    981     * @param v the long value to return
    982     * @return the long v, unchanged
    983     * @since 3.2
    984     */
    985    public static long CONST(final long v) {
    986        return v;
    987    }
    988
    989    /**
    990     * This method returns the provided value unchanged.
    991     * This can prevent javac from inlining a constant
    992     * field, e.g.,
    993     *
    994     * <pre>
    995     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
    996     * </pre>
    997     *
    998     * This way any jars that refer to this field do not
    999     * have to recompile themselves if the field's value
    1000     * changes at some future date.
    1001     *
    1002     * @param v the float value to return
    1003     * @return the float v, unchanged
    1004     * @since 3.2
    1005     */
    1006    public static float CONST(final float v) {
    1007        return v;
    1008    }
    1009
    1010    /**
    1011     * This method returns the provided value unchanged.
    1012     * This can prevent javac from inlining a constant
    1013     * field, e.g.,
    1014     *
    1015     * <pre>
    1016     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
    1017     * </pre>
    1018     *
    1019     * This way any jars that refer to this field do not
    1020     * have to recompile themselves if the field's value
    1021     * changes at some future date.
    1022     *
    1023     * @param v the double value to return
    1024     * @return the double v, unchanged
    1025     * @since 3.2
    1026     */
    1027    public static double CONST(final double v) {
    1028        return v;
    1029    }
    1030
    1031    /**
    1032     * This method returns the provided value unchanged.
    1033     * This can prevent javac from inlining a constant
    1034     * field, e.g.,
    1035     *
    1036     * <pre>
    1037     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
    1038     * </pre>
    1039     *
    1040     * This way any jars that refer to this field do not
    1041     * have to recompile themselves if the field's value
    1042     * changes at some future date.
    1043     *
    1044     * @param <T> the Object type
    1045     * @param v the genericized Object value to return (typically a String).
    1046     * @return the genericized Object v, unchanged (typically a String).
    1047     * @since 3.2
    1048     */
    1049    public static <T> T CONST(final T v) {
    1050        return v;
    1051    }
    1052
    1053}