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