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