Java调用方法并使用三元运算符并在参数中赋值?
我正在审查一些代码,我遇到了这个:
public static doSomething(String myString, String myString2) {
//Stuff
}
public static doAnotherThing(String myString) {
return doSomething(myString = myString != null ? myString.toLowerCase(): myString, null)
}
这到底是如何工作的?,我知道 .toLowerCase 结果字符串被分配给 myString (是的,我知道不好的做法,因为你不应该重新分配方法参数,事实上它们应该是最终的),但我不太确定该方法如何总是接收它需要的 2 个参数。
我知道当 myString 为 null 时它是如何工作的,或者至少我认为我知道,因为三元组有 myString, null,但我不太确定为什么当 myString 不为 null 时它会去那里?
I was reviewing some code and I came across this:
public static doSomething(String myString, String myString2) {
//Stuff
}
public static doAnotherThing(String myString) {
return doSomething(myString = myString != null ? myString.toLowerCase(): myString, null)
}
How is this working exactly?, I know the .toLowerCase resulting string is assigned to myString (yes I know bad practice since you are not supposed to reassign method parameters in fact they should be final), but I am not quite sure how does the method always receives the 2 parameters it needs.
I know how it works when myString is null or at least I think I do, since the ternary has myString, null, but I am not quite sure why it would go there when myString is not null?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
括号来拯救!
要理解这一点,您需要了解两件事:
Parenthesis to the rescue!
To understand this, you need to know two things:
它只是一个更复杂的版本:
或者甚至
Its just a more complicated version of:
or even
doSomething
接收两个参数,这两个参数都是字符串。在doAnotherThing
中:doSomething
的第一个参数是:null
如果myString
为null
,myString.toLowerCase()
否则。doSomething
的第二个参数始终为null
。像这样重写可能会更清楚:
doSomething
receives two parameters, both of which are strings. IndoAnotherThing
:doSomething
is:null
ifmyString
isnull
,myString.toLowerCase()
otherwise.doSomething
is alwaysnull
.It might be clearer rewritten like this:
这段代码将 myString 重新分配为 myString.toLowerCase(),或者不重新分配它。但是使用赋值运算符的行为会返回已分配的值,因此您实际上是在调用它:
您还应该注意字符串是不可变的,并且更改 doAnotherThing(String) 中 myString 的值不会影响原来的字符串。传递到方法中。
This piece of code reassigns myString to be either myString.toLowerCase(), or it doesn't reassign it. But the act of using the assignment operator returns the value that was assigned, thus you are essentially calling this:
You should also note that Strings are immutable, and that changing the value of myString in doAnotherThing(String) will not affect the String that was passed into the method.
代码很混乱,但我不确定问题是什么。赋值的结果就是赋值的值。
这
与
The code is confusing, but I am not sure what the problem is. The result of an assignment is the value assigned.
This
is the same as
从三元运算符分配到变量,如下所示:
更多示例:
http://alvinalexander.com/java/edu/pj/pj010018
Assign into variable from ternary operator like so:
More examples:
http://alvinalexander.com/java/edu/pj/pj010018