当我在构造函数中使用 StringBuffer/StringBuilder 创建一个新对象时,我似乎需要创建一个临时变量并将其传递给已初始化的类变量。也就是说,当我创建一个新实例时,我在构造函数中对 sNumber(下面的示例)所做的更改不会影响对象变量的值——除非我使用临时变量。例如:
public class Some_class {
public static class algorithm{
String sNumber = "";
algorithm(String num){
String temp = new StringBuilder(num).reverse().toString();
sNumber = temp;
//the below expression does not work:
//sNumber = new StringBuilder(num).reverse().toString();
}
我假设因为我将新的 StringBuilder/StringBuffer 对象命名为相同的名称,它会覆盖先前初始化的 sNumber 变量的值——但事实并非如此。有没有正确的方法来做到这一点?
最佳答案
I assumed that since I named the new StringBuilder/StringBuffer object the same name, it would override the value of the previously initialized sNumber variable
不,如果您将 StringBuilder 命名为与字段相同的名称,它将隐藏该字段。 (访问该字段的唯一方法是通过 this.sNumber
。)
你可以不用临时变量解决它,如下所示:
sNumber = new StringBuilder(num).reverse().toString();
(你在你的问题中说这不起作用,但它应该。只要确保你没有在构造函数中将 sNumber
声明为局部变量。如果它仍然不起作用,您需要在问题中包含错误消息。)
关于java - Java构造函数中的StringBuffer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27629536/