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