[英]How to use a reference multiple times just to do the stuff in a single sentence?
I have the code shown below.我有下面显示的代码。
StringBuffer sb = new StringBuffer(Integer.toBinaryString(n));
return (sb.charAt(sb.length() - k) == '1') ? Integer.parseInt(sb.deleteCharAt(sb.length() - k).insert(sb.length() - (k + 1), 0).toString(),2) : n;
Is it possible to use the sb
reference implicitly, ie just in order to write only the return sentence?是否可以隐式使用
sb
引用,即只写返回语句?
The only way you can "implicitly" use such a reference is when a method returns this
(ie the object you call it on) to allow that kind of call chaining.您可以“隐式”使用此类引用的唯一方法是当方法返回
this
引用(即您调用它的 object)以允许这种调用链。 For example StringBuilder.deleteCharAt()
does this and you already make use of this by chaining a call to insert
:例如
StringBuilder.deleteCharAt()
这样做并且您已经通过链接调用insert
来使用它:
sb.deleteCharAt(...).insert(...)
This kind of return value only makes sense in method that don't have any other return value to give (ie you obviously can't do that with sb.charAt
, because that returns a char
and can't also return the StringBuilder
itself).这种返回值仅在没有任何其他返回值可提供的方法中才有意义(即,您显然不能用
sb.charAt
做到这一点,因为它返回一个char
并且也不能返回StringBuilder
本身) .
But if you want to know if you can get rid of the sb
in sb.length()
for example: no, you pretty much can't.但是,如果您想知道是否可以摆脱
sb.length()
中的sb
,例如:不,您几乎不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.