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