Java util objects source

Class Objects

Этот класс состоит из static служебных методов для работы с объектами или проверки определенных условий перед операцией. Эти утилиты включают в себя null -safe или null -tolerant методы для вычисления хэш — код объекта, возвращая строку для объекта, сравнения двух объектов, а также проверки , если индексы или значения поддиапазона выходят за границы.

Method Summary

Проверяет, находится ли поддиапазон от fromIndex (включительно) до fromIndex + size ( исключая ) в пределах диапазона от 0 (включительно) до length (исключая).

Проверяет, находится ли поддиапазон от fromIndex (включительно) до fromIndex + size ( исключая ) в пределах диапазона от 0 (включительно) до length (исключая).

Проверяет, находится ли поддиапазон от fromIndex (включительно) до toIndex ( исключая ) в пределах диапазона от 0 (включительно) до length (исключая).

Проверяет, находится ли поддиапазон от fromIndex (включительно) до toIndex ( исключая ) в пределах диапазона от 0 (включительно) до length (исключая).

Проверяет, что указанная ссылка на объект не является null и выдает настраиваемое NullPointerException если это так.

Проверяет, что указанная ссылка на объект не является null и выдает настраиваемое NullPointerException если это так.

Возвращает первый аргумент, если он не равен null и в противном случае возвращает null второй аргумент.

Возвращает первый аргумент, если он не равен null и в противном случае возвращает null значение supplier.get() .

Возвращает строку, эквивалентную строке, возвращаемой Object.toString , если этот метод и hashCode не переопределены.

Возвращает результат вызова toString для первого аргумента, если первый аргумент не равен null и возвращает второй аргумент в противном случае.

Методы, объявленные в классе java.lang. Объект

Method Details

equals

public static boolean equals(Object a, Object b)

Возвращает true , если аргументы равны друг другу, и false в противном случае. Следовательно, если оба аргумента равны null , возвращается true . В противном случае, если первый аргумент не равен null , равенство определяется путем вызова метода equals первого аргумента со вторым аргументом этого метода. В противном случае возвращается false .

deepEquals

public static boolean deepEquals(Object a, Object b)

Возвращает true , если аргументы полностью равны друг другу, и false в противном случае. Два null значения полностью равны. Если оба аргумента являются массивами, алгоритм в Arrays.deepEquals используется для определения равенства. В противном случае равенство определяется с помощью метода equals первого аргумента.

hashCode

public static int hashCode(Object o)

hash

public static int hash(Object. values)

Создает хэш-код для последовательности входных значений. Хэш-код создается так, как если бы все входные значения были помещены в массив, и этот массив был хеширован путем вызова Arrays.hashCode(Object[]) .

Этот метод полезен для реализации Object.hashCode() для объектов, содержащих несколько полей. Например, если объект имеет три поля, x , y и z , можно написать:

@Override public int hashCode() < return Objects.hash(x, y, z); >

Предупреждение: Когда предоставляется одна ссылка на объект, возвращаемое значение не совпадает с хэш-кодом этой ссылки на объект. Это значение можно вычислить, вызвав hashCode(Object) .

Читайте также:  Доступ к объекту java

toString

public static String toString(Object o)

toString

public static String toString(Object o, String nullDefault)

Возвращает результат вызова toString для первого аргумента, если первый аргумент не равен null и возвращает второй аргумент в противном случае.

toIdentityString

public static String toIdentityString(Object o)

Возвращает строку, эквивалентную строке, возвращаемой Object.toString , если этот метод и hashCode не переопределены.

compare

public static int compare(T a, T b, Comparatorsuper T> c)

Возвращает 0, если аргументы идентичны, и c.compare(a, b) противном случае. Следовательно, если оба аргумента равны null возвращается 0.

Обратите внимание: если один из аргументов имеет значение null , NullPointerException может или не может быть сгенерировано в зависимости от того, какую политику упорядочивания, если таковая имеется, Comparator выбирает для значений null .

requireNonNull

public static T requireNonNull(T obj)

Проверяет, что указанная ссылка на объект не null . Этот метод предназначен в первую очередь для проверки параметров в методах и конструкторах, как показано ниже:

public Foo(Bar bar) < this.bar = Objects.requireNonNull(bar); >

Type Parameters: T — тип ссылки Parameters: obj — ссылка на объект для проверки на нуль Returns: obj , если не null Throws: NullPointerException — если obj равен null

requireNonNull

public static T requireNonNull(T obj, String message)

Проверяет, что указанная ссылка на объект не является null и выдает настраиваемое NullPointerException если это так. Этот метод предназначен в первую очередь для проверки параметров в методах и конструкторах с несколькими параметрами, как показано ниже:

public Foo(Bar bar, Baz baz) < this.bar = Objects.requireNonNull(bar, "bar must not be null"); this.baz = Objects.requireNonNull(baz, "baz must not be null"); >

Источник

Java util objects source

This class consists of static utility methods for operating on objects, or checking certain conditions before operation. These utilities include null -safe or null -tolerant methods for computing the hash code of an object, returning a string for an object, comparing two objects, and checking if indexes or sub-range values are out of bounds.

Method Summary

Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).

Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Methods declared in class java.lang.Object

Method Detail

equals

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null , true is returned and if exactly one argument is null , false is returned. Otherwise, equality is determined by using the equals method of the first argument.

Читайте также:  Dlib cuda python windows

deepEquals

Returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.

hashCode

hash

Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]) . This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x , y , and z , one could write:

@Override public int hashCode()

Warning: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object) .

toString

toString

public static String toString​(Object o, String nullDefault)

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

compare

Returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned. Note that if one of the arguments is null , a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.

requireNonNull

public static T requireNonNull​(T obj)

Checks that the specified object reference is not null . This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:

requireNonNull

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:

public Foo(Bar bar, Baz baz)

isNull

nonNull

requireNonNullElse

public static T requireNonNullElse​(T obj, T defaultObj)

requireNonNullElseGet

Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .

requireNonNull

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. Unlike the method requireNonNull(Object, String) , this method allows creation of the message to be deferred until after the null check is made. While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the message supplier are less than the cost of just creating the string message directly.

checkIndex

public static int checkIndex​(int index, int length)

checkFromToIndex

public static int checkFromToIndex​(int fromIndex, int toIndex, int length)

checkFromIndexSize

public static int checkFromIndexSize​(int fromIndex, int size, int length)

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Читайте также:  Тег IMG

Источник

Java util objects source

This class consists of static utility methods for operating on objects. These utilities include null -safe or null -tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

Method Summary

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Methods inherited from class java.lang.Object

Method Detail

equals

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null , true is returned and if exactly one argument is null , false is returned. Otherwise, equality is determined by using the equals method of the first argument.

deepEquals

Returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.

hashCode

hash

Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]) . This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x , y , and z , one could write:

@Override public int hashCode()

Warning: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object) .

toString

toString

public static String toString(Object o, String nullDefault)

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

compare

Returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned. Note that if one of the arguments is null , a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.

requireNonNull

public static T requireNonNull(T obj)

Checks that the specified object reference is not null . This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:

requireNonNull

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:

Источник

Оцените статью