Return 中的值 java 当有 if 且没有 else 时

Return value in java when there is if and no else

我被困在一个简单的方法中,因为我无法编译它。 我正在为 objList 的每个循环做,这是一个 ArrayList<anObject>。我知道编译器无法编译它,因为没有 "Top-Level Return".

anObject getObjByID(int id){           
    for(anObject obj : objList ){      
      if (obj.getID() == id){
        return node;        
      }        
    }           
  }

另外我也不知道return如果条件不满足怎么办。我不能 return anObject 因为没有。 希望大家能帮我提供解决方案。

如果您的搜索 object 没有找到,您必须 return 一些 default 值。你可以在这里 return null

anObject getObjByID(int id){           
  for(anObject obj : objList ){      
    if (obj.getID() == id){
     return node;       // will return when searching matched 
    }        
  }          
  return null; // will return matching not found.
}

抛出 exception 是您可以使用的另一种选择。

anObject getObjByID(int id){           
    for(anObject obj : objList ){      
      if (obj.getID() == id){
        return node;        
         }        
    }
  throw new MyException("Element Not Found");           
}
anObject getObjByID(int id){           
    for(anObject obj : objList ){      
      if (obj.getID() == id){
        return node;        
      }        
    } 
      return null;
  }

您可以简单地抛出带有特定消息的异常,我认为这是一个很好的解决方案。但是如果没有被捕获,这将中断程序的流程。

anObject getObjByID(int id){           
        for(anObject obj : objList ){      
          if (obj.getID() == id){
            return node;        
             }        
        }
      thronw new UserDefinedException("Item not found in list");           
}

基本上有两种不同的选择:

  1. 找不到对象是一个有效的场景;那么你可能 return null。或者可能是一些表示 空搜索结果 的特殊 Singleton 对象 - 因为许多人认为在这样的上下文中使用 null 是一个坏主意(它强制你的方法的调用者检查是否为空;或者你冒 NullPointerExceptions)

  2. 的风险
  3. 找不到对象是不应该出现的错误:那你直接在循环后抛出异常即可。

您需要在每种情况下 return 一个值。 Null 在这里似乎不错。

anObject getObjByID(int id){           
  for(anObject obj : objList ){      
    if (obj.getID() == id){
      return node;        
    }        
  }  
  return null;         
}

你总是需要考虑你可以调用这个方法并且if语句不等于true。因此你的方法应该是什么return?它需要一个 anObject 类型的对象,或者你 return null。如果这种情况永远不会发生,有时抛出异常是有意义的。

Also I don't know what to return when the conditions doesn't met.

这真的取决于你的逻辑。如果你想允许 null,你不应该 return 如果没有找到对象,你可以创建自己的对象来指示找不到对象或抛出一个稍后将被捕获的异常.

如果您的对象无法 null,您可以假定 null 在未找到对象时被 return 编辑。

如果您使用的是 Java 8,则有更多更好的选择,请参阅 Optional

请遵循 Java 命名约定

您可以做几件事:

  • Return null

不过,这不是最佳实践,因为该方法的客户端将被迫处理可能 returned null(如果他不这样做,则 NullPointerException 可以是抛出)。

您的方法如下所示:

anObject getObjByID(int id){           
    for(anObject obj : objList ){      
        if (obj.getID() == id){
            return obj;        
        }        
    }            
    return null;
}

在这种情况下,客户端将不得不处理null个结果的情况:

anObject result = getObjByID(someId);
if (result != null) {
    //proceed
}

  • 投掷 IllegalArgumentException(或其他一些 Exception

您可以抛出 IllegalArgumentException 来表示提供的 id 没有相应的 Node。客户端将被强制处理异常。

您的方法如下所示:

anObject getObjByID(int id) throws IllegalArgumentException {           
    for(anObject obj : objList ){      
        if (obj.getID() == id){
            return obj;        
        }        
    }            
    throw new IllegalArgumentException("Invalid index");
}

客户端必须处理异常:

try {
    anObject result = getObjByID(someId);
    //proceed
} catch (IllegalArgumentException e) {
    //handle the exception
}

Java8 介绍了 Optonal<T> class,这有点像外星人 - 它可能存在也可能不存在。将方法的 return 类型指定为 Optional<T> 有助于客户端意识到 return 值可能存在,也可能不存在。

您的方法如下所示:

Optional<anObject> getObjByID(int id){           
    Optional<anObject> result = Optional.empty();
    for(anObject obj : objList ){      
        if (obj.getID() == id){
            result = Optional.of(obj);        
        }        
    }            
    return result;
}

客户端会这样使用这个方法:

Optional<anObject> result = getObjByID(someId);
if (result.isPresent()) {
    anObject realResultObject = result.get();
}

来自ls-8.4.7

If a method is declared to have a return type, then a compile-time error occurs if the body of the method can complete normally (§14.1).

意思是 return 您期望的对象完成方法或 return null.

jls-8.4.5

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.

A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:

If R1 is void then R2 is void.

If R1 is a primitive type, then R2 is identical to R1.

If R1 is a reference type then:

R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or

R1 = |R2|

表示如果您使用 java 7,则 return 类型应与上述条件相同。

如果您正在使用 java 8 检查 JLS 8.4.5. Method Result