< prev index next >

src/java.base/share/classes/java/util/Objects.java

Print this page

  1 /*
  2  * Copyright (c) 2009, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.util;
 27 

 28 import jdk.internal.util.Preconditions;
 29 import jdk.internal.vm.annotation.ForceInline;
 30 
 31 import java.util.function.Supplier;
 32 
 33 /**
 34  * This class consists of {@code static} utility methods for operating
 35  * on objects, or checking certain conditions before operation.  These utilities
 36  * include {@code null}-safe or {@code null}-tolerant methods for computing the
 37  * hash code of an object, returning a string for an object, comparing two
 38  * objects, and checking if indexes or sub-range values are out of bounds.
 39  *
 40  * @since 1.7
 41  */
 42 public final class Objects {
 43     private Objects() {
 44         throw new AssertionError("No java.util.Objects instances for you!");
 45     }
 46 
 47     /**

141 
142     /**
143      * {@return the result of calling {@code toString} on the first
144      * argument if the first argument is not {@code null} and the
145      * second argument otherwise}
146      *
147      * @param o an object
148      * @param nullDefault string to return if the first argument is
149      *        {@code null}
150      * @see Objects#toString(Object)
151      */
152     public static String toString(Object o, String nullDefault) {
153         return (o != null) ? o.toString() : nullDefault;
154     }
155 
156     /**
157      * {@return a string equivalent to the string returned by {@code
158      * Object.toString} if that method and {@code hashCode} are not
159      * overridden}
160      *









161      * @implNote
162      * This method constructs a string for an object without calling
163      * any overridable methods of the object.
164      *
165      * @implSpec
166      * The method returns a string equivalent to:<br>
167      * {@code o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o))}
168      *
169      * @param o an object
170      * @throws NullPointerException if the argument is null
171      * @see Object#toString
172      * @see System#identityHashCode(Object)
173      * @since 19
174      */
175     public static String toIdentityString(Object o) {
176         requireNonNull(o);
177         return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
178     }
179 
















































































































180     /**
181      * {@return 0 if the arguments are identical and {@code
182      * c.compare(a, b)} otherwise}
183      * Consequently, if both arguments are {@code null} 0
184      * is returned.
185      *
186      * <p>Note that if one of the arguments is {@code null}, a {@code
187      * NullPointerException} may or may not be thrown depending on
188      * what ordering policy, if any, the {@link Comparator Comparator}
189      * chooses to have for {@code null} values.
190      *
191      * @param <T> the type of the objects being compared
192      * @param a an object
193      * @param b an object to be compared with {@code a}
194      * @param c the {@code Comparator} to compare the first two arguments
195      * @see Comparable
196      * @see Comparator
197      */
198     public static <T> int compare(T a, T b, Comparator<? super T> c) {
199         return (a == b) ? 0 :  c.compare(a, b);

  1 /*
  2  * Copyright (c) 2009, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.util;
 27 
 28 import jdk.internal.javac.PreviewFeature;
 29 import jdk.internal.util.Preconditions;
 30 import jdk.internal.vm.annotation.ForceInline;
 31 
 32 import java.util.function.Supplier;
 33 
 34 /**
 35  * This class consists of {@code static} utility methods for operating
 36  * on objects, or checking certain conditions before operation.  These utilities
 37  * include {@code null}-safe or {@code null}-tolerant methods for computing the
 38  * hash code of an object, returning a string for an object, comparing two
 39  * objects, and checking if indexes or sub-range values are out of bounds.
 40  *
 41  * @since 1.7
 42  */
 43 public final class Objects {
 44     private Objects() {
 45         throw new AssertionError("No java.util.Objects instances for you!");
 46     }
 47 
 48     /**

142 
143     /**
144      * {@return the result of calling {@code toString} on the first
145      * argument if the first argument is not {@code null} and the
146      * second argument otherwise}
147      *
148      * @param o an object
149      * @param nullDefault string to return if the first argument is
150      *        {@code null}
151      * @see Objects#toString(Object)
152      */
153     public static String toString(Object o, String nullDefault) {
154         return (o != null) ? o.toString() : nullDefault;
155     }
156 
157     /**
158      * {@return a string equivalent to the string returned by {@code
159      * Object.toString} if that method and {@code hashCode} are not
160      * overridden}
161      *
162      * @apiNote
163      * <div class="preview-block">
164      *      <div class="preview-comment">
165      *          Note that, like ==, the hash code string exposes information about a value object's
166      *          private fields that might otherwise be hidden by an identity object.
167      *          Developers should be cautious about storing sensitive secrets in value object fields.
168      *      </div>
169      * </div>
170      *
171      * @implNote
172      * This method constructs a string for an object without calling
173      * any overridable methods of the object.
174      *
175      * @implSpec
176      * The method returns a string equivalent to:<br>
177      * {@code o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o))}
178      *
179      * @param o an object
180      * @throws NullPointerException if the argument is null
181      * @see Object#toString
182      * @see System#identityHashCode(Object)
183      * @since 19
184      */
185     public static String toIdentityString(Object o) {
186         requireNonNull(o);
187         return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
188     }
189 
190     /**
191      * {@return {@code true} if the input is a non-null reference
192      * to an object with identity, and {@code false} otherwise}
193      *
194      * <p>If the object is an instance of a concrete {@linkplain Class#isValue()
195      * value class}, it does not have identity and the result will be
196      * {@code false}. All other objects, including arrays, are identity objects
197      * and the result will be {@code true}.
198      *
199      * <p>This method returns {@code false} if and only if the parameter is
200      * {@code null} or if the parameter represents a value object when preview
201      * features are enabled.  All objects are identity objects when preview
202      * features are disabled; consequently, this method behaves the same as
203      * {@link #nonNull Objects.nonNull} when preview features are disabled.
204      *
205      * @apiNote
206      * If the parameter is {@code null}, there is no object
207      * and hence no identity; the result is {@code false}.
208      * To test for a value object use:
209      * {@snippet type="java" :
210      *     if (obj != null && !Objects.hasIdentity(obj)) {
211      *         // obj is a non-null value object
212      *     }
213      * }
214      * @param obj an object or {@code null}
215      * @since 28
216      */
217     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
218     public static boolean hasIdentity(Object obj) {
219         return (obj == null) ? false : !obj.getClass().isValue();
220     }
221 
222     /**
223      * Checks that the specified object reference is an identity object.
224      * <p>
225      * This method throws an {@code IdentityException} if and only if the
226      * parameter represents a value object when preview features are enabled.
227      * All objects are identity objects when preview features are disabled;
228      * consequently, this method behaves the same as {@link #requireNonNull(Object)
229      * Objects.requireNonNull} when preview features are disabled.
230      *
231      * @param obj the object reference to check for identity
232      * @param <T> the type of the reference
233      * @return {@code obj} if {@code obj} is an identity object
234      * @throws NullPointerException if {@code obj} is {@code null}
235      * @throws IdentityException if {@code obj} is not an identity object
236      * @since 28
237      */
238     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective = true)
239     @ForceInline
240     public static <T> T requireIdentity(T obj) {
241         Objects.requireNonNull(obj);
242         if (!hasIdentity(obj))
243             throw new IdentityException(obj.getClass().getName() + " is not an identity class");
244         return obj;
245     }
246 
247     /**
248      * Checks that the specified object reference is an identity object.
249      * <p>
250      * This method throws an {@code IdentityException} if and only if the
251      * parameter represents a value object when preview features are enabled.
252      * All objects are identity objects when preview features are disabled;
253      * consequently, this method behaves the same as {@link #requireNonNull(Object, String)
254      * Objects.requireNonNull} when preview features are disabled.
255      *
256      * @param obj the object reference to check for identity
257      * @param message detail message to be used in the event that an
258      *        {@code IdentityException} is thrown; may be null
259      * @param <T> the type of the reference
260      * @return {@code obj} if {@code obj} is an identity object
261      * @throws NullPointerException if {@code obj} is {@code null}
262      * @throws IdentityException if {@code obj} is not an identity object
263      * @since 28
264      */
265     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective = true)
266     @ForceInline
267     public static <T> T requireIdentity(T obj, String message) {
268         Objects.requireNonNull(obj);
269         if (!hasIdentity(obj))
270             throw new IdentityException(message);
271         return obj;
272     }
273 
274     /**
275      * Checks that the specified object reference is an identity object.
276      * <p>
277      * This method throws an {@code IdentityException} if and only if the
278      * parameter represents a value object when preview features are enabled.
279      * All objects are identity objects when preview features are disabled;
280      * consequently, this method behaves the same as {@link #requireNonNull(Object, Supplier)
281      * Objects.requireNonNull} when preview features are disabled.
282      *
283      * @param obj the object reference to check for identity
284      * @param messageSupplier supplier of the detail message to be
285      *        used in the event that an {@code IdentityException} is thrown; may be null
286      * @param <T> the type of the reference
287      * @return {@code obj} if {@code obj} is an identity object
288      * @throws NullPointerException if {@code obj} is {@code null}
289      * @throws IdentityException if {@code obj} is not an identity object
290      * @since 28
291      */
292     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective = true)
293     @ForceInline
294     public static <T> T requireIdentity(T obj, Supplier<String> messageSupplier) {
295         Objects.requireNonNull(obj);
296         if (!hasIdentity(obj))
297             throw new IdentityException(messageSupplier == null ?
298                     null : messageSupplier.get());
299         return obj;
300     }
301 
302     /**
303      * {@return 0 if the arguments are identical and {@code
304      * c.compare(a, b)} otherwise}
305      * Consequently, if both arguments are {@code null} 0
306      * is returned.
307      *
308      * <p>Note that if one of the arguments is {@code null}, a {@code
309      * NullPointerException} may or may not be thrown depending on
310      * what ordering policy, if any, the {@link Comparator Comparator}
311      * chooses to have for {@code null} values.
312      *
313      * @param <T> the type of the objects being compared
314      * @param a an object
315      * @param b an object to be compared with {@code a}
316      * @param c the {@code Comparator} to compare the first two arguments
317      * @see Comparable
318      * @see Comparator
319      */
320     public static <T> int compare(T a, T b, Comparator<? super T> c) {
321         return (a == b) ? 0 :  c.compare(a, b);
< prev index next >