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