void函数中return语句的用途是什么

时间:2012-12-22 05:43:41

标签: java android return

我是java新手,return;是什么意思?是break吗?

  public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }

如果第二个imageViewReused(photoToLoad)返回true,BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad)将不会被执行,对吧?

7 个答案:

答案 0 :(得分:5)

是的,有相似之处,但也存在差异

  • break - 将停止循环并切换条件。只能用于switch和loop语句
  • return - 将完成函数执行,但不会执行此关键字的以下语句。只能用于任何功能。

在void函数中使用 return 关键字

如果您在此类

的void函数中使用return
void trySomething()
{
  Log.i("Try", "something");

  return;
  Log.e("Try", "something"); 
}

此函数的执行已完成,但下面的语句将不会执行。

break 关键字

的使用情况

用于任何循环语句

void tryLoop()
{
   while(true)
   {
      Log.d("Loop", "Spamming! Yeah!");
      break;
   }
}

循环将停止并继续此函数的其余语句

用于切换条件

void trySwitch()
{ 
   int choice = 1;
   switch(choice)
   {
      case 0:
        Log.d("Choice", "is 0");
        break;
      case 1:
        Log.d("Choice", "is 1");
      case 2:
        Log.d("Choice", "is 2");
   }
}

在切换条件下使用break也与循环相同。省略break将继续切换条件。

答案 1 :(得分:1)

是的,你可以像休息一样使用它。

答案 2 :(得分:1)

是的,return会中断您下次执行相同的阻止。

了解有关return check this

的更多信息

答案 3 :(得分:1)

return结束调用它时出现的方法的执行。对于void方法,它只是退出方法体。对于非void方法,它实际上返回一个值(即return X)。请注意try-finally:请记住,即使return区块中tryfinally block也会被执行:

public static void foo() {
    try {
        return;
    } finally {
        System.out.println("foo");
    }
}

// run foo in main
foo

This是了解return的更多信息的好参考。


  

是否像break

从某种意义上说,这两个陈述“结束”一个正在运行的过程; return结束方法,break结束循环。然而,重要的是要知道两者之间的差异以及何时应该使用它们。

  

如果第二个imageViewReused(photoToLoad)返回trueBitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad)将无法执行,对吧?

正确 - 如果执行return - 语句的正文并且不会达到后续语句,则该方法将为“if”。

答案 4 :(得分:0)

一个函数的执行完成,当涉及到return语句,然后它返回到它的调用代码。在你的情况下,

如果imageViewReused(photoToLoad)为真,那么return之后的代码块将无法执行。

答案 5 :(得分:0)

这里返回作为函数的结尾。  您可以通过将代码更改为

来避免它
 public void run() {
        if(!imageViewReused(photoToLoad))
        {
          Bitmap bmp=getBitmap(photoToLoad.url);
          memoryCache.put(photoToLoad.url, bmp);
          if(!imageViewReused(photoToLoad))
          {
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
          }
    }

答案 6 :(得分:-1)

返回语句会跳过函数范围的剩余执行。

值得一读:

  1. returnhttp://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
  2. breakhttp://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
相关问题