Java 使用泛型时如何返回整数? //返回当前元素的值(或-1) 公共T GetValue() { 节点温度=头; while(温度!=电流) { 温度=下一个温度; if(temp==null) { 返回-1; } } 返回温度数据; }
我的代码应该获取当前元素的值并返回该值。如果找不到,则返回-1。在不使用if语句的情况下运行此代码会导致空指针异常。由于泛型,我无法使用if语句运行代码。如果Java 使用泛型时如何返回整数? //返回当前元素的值(或-1) 公共T GetValue() { 节点温度=头; while(温度!=电流) { 温度=下一个温度; if(temp==null) { 返回-1; } } 返回温度数据; },java,generics,nullpointerexception,Java,Generics,Nullpointerexception,我的代码应该获取当前元素的值并返回该值。如果找不到,则返回-1。在不使用if语句的情况下运行此代码会导致空指针异常。由于泛型,我无法使用if语句运行代码。如果t是整数,则只能返回-1;但那就不是一般的了 您需要某种特殊值,不能将其误认为是t的“真实”实例。例如,您可以将返回类型更改为Optional,以便返回Optional.empty(),以指示未找到值 // returns the value of the current element (or -1) public T GetVa
t
是整数,则只能返回-1;但那就不是一般的了
您需要某种特殊值,不能将其误认为是t
的“真实”实例。例如,您可以将返回类型更改为Optional
,以便返回Optional.empty()
,以指示未找到值
// returns the value of the current element (or -1)
public T GetValue()
{
Node<T> temp = head;
while(temp != curr)
{
temp = temp.next;
if(temp == null)
{
return -1;
}
}
return temp.data;
}
public可选GetValue(){
// ...
if(temp==null)
{
返回可选的.empty();
}
// ...
返回可选的(温度数据);
}
或者,您可以向类的构造函数提供一个“not found”值,并在找不到某些内容时返回该值:
public Optional<T> GetValue() {
// ...
if(temp == null)
{
return Optional.empty();
}
// ...
return Optional.of(temp.data);
classyourclass{
private final T notFoundValue;//在构造函数中赋值。
// ...
公共T GetValue(){
// ...
if(temp==null)
{
返回notFoundValue;
}
// ...
返回温度数据;
}
}
但是您必须非常小心地处理notFoundValue
被返回的可能性;通过将不同(但相关)类型的内容返回到T
,例如Optional
,使其显式化,是确保执行此处理的好方法。函数应该返回int,或者应该返回-1。如果它的返回类型是T(并且T不是整数的某个超类型),则不能返回-1。您的要求没有意义。为了完整性,当方法返回Optional
时,使用Integer
ForT
的调用方可以使用GetValue().orElse(-1)
来获得所需的行为。
class YourClass<T> {
private final T notFoundValue; // Assign in constructor.
// ...
public T GetValue() {
// ...
if(temp == null)
{
return notFoundValue;
}
// ...
return temp.data;
}
}