2012-07-25 80 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