Вернуть null в методе, который возвращает двойные значения java
Я пытаюсь проверить нулевой ввод в начале метода. И если найдено true, я хочу вернуть null, даже если метод обычно возвращает двойные значения.
Мне нужно сохранить тип метода как двойной
public double computeMean (double[] grades) < if (grades == null) < return null;
Невозможно преобразовать из null в double
Точно так, как написано в ошибке. Вы не можете вернуть null там, где ожидается примитив. Вы могли бы, если бы подпись метода была для Double .
2 ответа
Объяснение
null - это значение, которое может использоваться только для объектов. Однако double является примитивом, он не использует объектную систему. Вот почему вы не можете вернуть null , если вы указали double как возвращаемый тип.
Итак, каковы ваши варианты?
Double обертка
Вместо этого вы можете использовать Double , класс-оболочку для double , который использует объектную систему.
Поскольку Java обеспечивает автоматическое преобразование между double и Double , когда это необходимо (автобоксирование), это может быть весьма удобно в использовании.
Обратите внимание, что использование Double приводит к значительным накладным расходам только для небольшого double и что люди часто забывают проверять наличие null при преобразовании Double в double . Т.е.
// foo() returns Double double value = foo(); // Bad code, it could be null!
Вместо этого пользователи должны не забыть проверить полученное значение:
Double result = foo(); if (result == null) < . >else
OptionalDouble
Современная и, вероятно, лучшая альтернатива - использовать Optional (для этого вам понадобится как минимум Java 8).
Он был разработан для использования всякий раз, когда метод, естественно, может иногда не возвращать результат. Например, если массив передан в пустом . Этот случай совершенно нормален и не может считаться ошибкой.
Это также решает проблему того, что пользователи забывают проверить результат. Optional заставляет их проверить это, иначе они не смогут получить базовое значение.
Чтобы избежать накладных расходов на производительность Optional (снова класс-оболочка), существует также OptionalDouble , который внутренне использует double (примитив). Вот код:
public OptionalDouble computeMean(double[] grades) < if (grades == null) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); >
OptionalDouble result = computeMean(. );
Оттуда у пользователя есть несколько вариантов (см. документация ), например
double value = result.orElse(10.4); // or double value = result.orElseThrow(); // or if (!result.isPresent()) < . >else
Исключение
Последний вариант - просто выбросить исключение. Вы должны учитывать это всякий раз, когда пользователь делает что-то, что не предназначено и против того, что вы считаете правильным использованием (укажите это в документации ваших методов).
Я бы сказал, что в вашей конкретной ситуации это так. Невозможно вычислить mean на null . Это отличается от передачи пустого массива, где я бы выбрал пустой Optional . Для массива null я бы выбросил исключение, чтобы указать на неправильное использование.
Хорошим исключением для этой ситуации является IllegalArgumentException , вот код:
public double computeMean(double[] grades) < if (grades == null) < throw IllegalArgumentException("Grades must not be null!"); >. >
Другое идиоматическое исключение именно для этого варианта использования - выбросить NullPointerException . Есть даже компактный вспомогательный метод, позволяющий сделать все это в одной строке:
public double computeMean(double[] grades) < Objects.requireNonNull(grades); // Yes, thats it . >
Результат
Собирая все это вместе, я бы внес следующие два изменения:
- Бросьте NullPointerException , если grades равно null , используя Objects#requireNonNull
- Вернуть пустой OptionalDouble , если grades пуст
public OptionalDouble computeMean(double[] grades) < Objects.requireNonNull(grades); if (grades.length == 0) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); >
Double класс-оболочка (обратите внимание на заглавную букву "d")
Не примитивный тип double в качестве возвращаемого типа, если вы хотите иметь возможность возвращать null .
Я бы выбросил исключение. Это случай ошибки. В противном случае верните пустой OptionalDouble , если это считается правильным использованием метода. Возвращение null кажется плохим выбором по разным причинам. И это кажется таким не-современным стилем.
[Solved]-Return null in a method that returns doubles java-Java
not double primitive type as your return type, if you want to be able to return null .
arkantos 442
Explanation
null is a value that can only be used for objects. A double however is a primitive, it does not use the object-system. Which is why you can not return null if you specified double as return type.
Double wrapper
You can instead use Double , the wrapper class for double which uses the object-system.
Since Java provides automatic conversion between double and Double whenever needed (autoboxing), this can be quite handy to use.
Note that using Double brings quite some overhead to just a small double and that people regularly tend to forget to check for null when converting a Double to a double . I.e.
// foo() returns Double double value = foo(); // Bad code, it could be null!
Instead, users must remember to check the resulting value:
Double result = foo(); if (result == null) < . >else
OptionalDouble
The modern, and probably better alternative, is to use Optional (you need at least Java 8 for this).
It was designed to be used whenever a method naturally might sometimes not return a result. For example if the array passed in empty. That case is completely okay and not to be considered as error.
This also solves the problem of users forgetting to check the result. Optional forces them to check it, else they can not get hands on the underlying value.
In order to avoid the performance overhead of Optional (wrapper class again), there is also OptionalDouble which internally uses double (primitive). Here is the code:
public OptionalDouble computeMean(double[] grades) < if (grades == null) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); >
OptionalDouble result = computeMean(. );
From there the user has a couple of options (see the documentation), for example
double value = result.orElse(10.4); // or double value = result.orElseThrow(); // or if (!result.isPresent()) < . >else
Exception
The last option is to actually just throw an exception. You should consider this whenever an user is doing something that is not intended and against what you consider correct usage (indicate this in your methods documentation).
I would actually say that in your specific situation, this is the case. It is impossible to compute a mean on null . It is different to passing in an empty array, where the I would go for an empty Optional . For a null array I would throw an exception, to indicate a bad usage.
A good exception for this situation is IllegalArgumentException , here is the code:
public double computeMean(double[] grades) < if (grades == null) < throw IllegalArgumentException("Grades must not be null!"); >. >
Another idiomatic exception for exactly this use case is to throw NullPointerException . There is even a compact helper method to do all of this in one line:
public double computeMean(double[] grades) < Objects.requireNonNull(grades); // Yes, thats it . >
Result
Putting all of that together, I would do the following two changes:
- Throw NullPointerException if grades is null , using Objects#requireNonNull
- Return an empty OptionalDouble if grades is empty
public OptionalDouble computeMean(double[] grades) < Objects.requireNonNull(grades); if (grades.length == 0) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); >
Zabuzard 23663
Related Query
- A simple Java code that returns unexpectedly false while it is intened to return true
- Java Generics: override method that differs in parameterized return type
- Why does java allow a method which always throws an exception to declare the return type as that exception?
- If a LinkedList is empty, return nothing from a method that returns an int?
- Method that returns any type in Java
- Java generics calling a method that returns object
- In Java 8, how do I make a method reference to a method that takes no parameters and returns void?
- General Java Method that Queries DB and Returns Results in Json Format
- Constructing a Java method that returns a primitive data type that is decided by the input?
- Java method that returns sum of number series and takes series array as parameter
- How to overwrite the hashcode method that returns a unique hashcode value with its unique entity ID in my defined Java object?
- Java Unit Testing method that uses new Date() for current date
- Java - modified compareTo method says it needs to return an int, but it should be returning one
- Using Java generics in interfaces that return collections. Best practice? Pitfalls?
- Java mail api message id returns null in some cases
- Queue.Poll() is return null but Queue.size() >0 in java queue
- Java 8 -Two interfaces contain default methods with the same method signature but different return types, how to override?
- Java language spec: "an invocation of Class" as return type of method in annotation type
- Implementing a method that is present in both interface and abstract class in java
- Rhino: How to return an Integer from Java method called by JavaScript?
- scala override java class method that references inner class
- Java Generic type inference derived from method return type
- I need to have a java method that can be accessed from anywhere within my API but cannot be accessed from the application using the API
- HibernateTemplate Get method returns an object with null values
- Test POST method that return ResponseEntity<> in Spring
- JNI passing a null argument to Java method
- Method that returns true or false at x percentage
- Java and SQL : return null or throw exception?
- A java method that has a generic parameter- why can't I pass an object with a generic parameter that is a subclass of the method arguments?
- this == null in java , After that also execution why Continues?
More Query from same tag
- Restricted access on method call using Java polymorphism
- Running operations in parallel while preserving in-order, incremental output
- Disable "flinging" in android ScrollView?
- Determine if there is/are escape character(s) in string
- Why Quartz 2.* does not cleanup indexes in Postgres database?
- Java: Dealing with Exponentiation
- Mock Object Libraries in Java
- Network quality indicator on a webapp
- Copy object properties by direct field access
- How to check if a string contains uppercase java
- How do I instantiate a generic type?
- How to turn an array of Strings into an Array of Ints?
- How to check a string is float or int?
- Recursively pass counter variable in Java
- When do we use interface extends interface
- AES encryption/decryption from Android to server
- NoSuchMethodError at org.apache.hadoop.hdfs.DFSInputStream
- How can i count this variables in my DB?
- Run JUnit tests automatically before commit in Eclipse
- Secure way to implement social security number
- Maven dependencies not accessible in Java
- Implement singleton with static access modifier in Java
- Another way of writing If statement in java
- How to find time spent by mappers and reducers in Hadoop?
- What could make this dsl easier to type or read?
- Difference between BoundedFifoBuffer and CircularFifoBuffer?
- What is causing my java.lang.NullPointerException error when I try to run this program?
- Returning Subclass of generic superclass in a superclass method
- Java Generics Name type parameter without requiring it
- grails - inheritance in domain class - inherited columns into base tables