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