2012-07-25 82 views
1

在Java的String.class,我看到這個使用?在return語句

public String substring(int beginIndex, int endIndex){ 
    //if statements 
    return ((beginIndex == 0) && (endIndex == count)) ? this: 
    new String (offset + beginIndex, endIndex - beginIndex, value); 
} 

什麼 '?'在做什麼?當我們談論這個問題時,任何人都可以在return語句中解釋'new String'發生了什麼?那是一種有條件的嗎?

+1

這是一個內嵌的if表達式,條件?如果爲true:if false' http://www.devdaily.com/java/edu/pj/pj010018 – asawyer 2012-07-25 19:38:48

+0

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html – BalusC 2012-07-25 19:40:01

+0

downvote?謹慎解釋? – Daniel 2012-07-25 19:46:21

回答

5

這是一個ternary operator和它等價於:

if((beginIndex == 0) && (endIndex == count)) { 
    return this; 
} else { 
    return new String (offset + beginIndex, endIndex - beginIndex, value); 
} 
2
return boolValue ? a : b; 

將返回a如果boolValue是真實的,否則b。這是一個簡短的形式ifelse

1
return ((beginIndex == 0) && (endIndex == count)) ? this: 
new String (offset + beginIndex, endIndex - beginIndex, value); 

是一樣的:

if ((beginIndex == 0) && (endIndex == count)) 
    return this; 
else 
    return new String (offset + beginIndex, endIndex - beginIndex, value); 
0

這是一個Ternary Operator,在許多編程語言不只是Java中使用。將所有內容放在一行中非常有用,基本上與此類似:

if (endIndex == count && beginIndex == 0) 
{ 
    return this; 
} 
else 
{ 
    return new String (offset + beginIndex, endIndex - beginIndex, value); 
} 

新字符串只是一個構造函數。

1

?:三元運算符a ? b : c相當於:

if (a) then b; else c; 

誰能解釋什麼,在return語句

三元說 '新字符串' 發生運算符是這個條件語句中的return,但new String是沒有條件的,它只是構造一個新的String:取決於條件,這return語句返回之一:

  • this,或
  • String對象
4

這是一個三元運算符。

Cake mysteryCake = isChocolate() ? new Cake("Yummy Cake") : new Cake("Gross Cake"); 

把它看成是:

如果該條件爲真,分配第一值,否則,分配的第二個。

return語句,變成:

如果這個條件爲真,則返回的第一件事,否則返回第二個。

+1

不錯的例子:D – Baz 2012-07-25 19:42:36

+0

是的,但是它使用了錯誤的編碼習慣,因爲它調用了一個靜態方法,只有在Cake創建後才能知道! – BlackVegetable 2012-07-25 19:43:16

+0

+1爲真實世界的例子;-)。順便說一句,考慮移除'isChocolate()'的花括號,可能會更好看 – 2012-07-25 19:43:48