1

JavaのString.classで、これが表示されます

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

「?」とは何ですか やってる?この件について話している間、returnステートメントでその「新しい文字列」で何が起こっているのかを誰かが説明できますか?それはある種の条件付きですか?

4

6 に答える 6

5

It's a ternary operator and it is equivalent to:

if((beginIndex == 0) && (endIndex == count)) {
  return this;
} else { 
  return new String (offset + beginIndex, endIndex - beginIndex, value);
}
于 2012-07-25T19:38:54.210 に答える
4

This is a ternary operator.

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

Think of it as:

If this condition is true, assign the first value, otherwise, assign the second.

For a return statement, that becomes:

If this condition is true, then return the first thing, otherwise return the second.

于 2012-07-25T19:42:09.330 に答える
2
return boolValue ? a : b;

will return a if boolValue is true and b otherwise. It's a short form of if else.

于 2012-07-25T19:39:18.983 に答える
1
return ((beginIndex == 0) && (endIndex == count)) ? this:
 new String (offset + beginIndex, endIndex - beginIndex, value);

is the same of:

if ((beginIndex == 0) && (endIndex == count)) 
    return this;
else 
    return new String (offset + beginIndex, endIndex - beginIndex, value);
于 2012-07-25T19:39:38.950 に答える
1

The ?: is the ternary operator: a ? b : c is equivalent to:

if (a) then b; else c;

can anyone explain whats happening with that 'new String' in the return statement

The ternary operator is the conditional in this return statement, but new String is no sort of conditional, it is simply constructing a new String: depending on the conditional, this return statement returns either:

  • this, or
  • a new String object
于 2012-07-25T19:41:57.453 に答える
0

It is a Ternary Operator, used in many programming languages no just Java. It is quite useful to put everything in a single line basically it equals this:

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

New String is just a constructor.

于 2012-07-25T19:41:20.983 に答える