问题描述
我有这个方法,
public static void main(String[] args) {
String s = "Java";
StringBuilder buffer = new StringBuilder(s);
change(buffer);
System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(3));
System.out.println(buffer);
}
private static void change(StringBuilder buffer) {
buffer.append(" and HTML");
}
当我使用StringBuilder运行代码时,我收到错误消息,
构造函数StringBuilder(String)未定义
方法charAt(int)未定义类型StringBuilder
When I run the code using StringBuilder I get error message ,"The constructor StringBuilder(String) is undefinedThe method charAt(int) is undefined for the type StringBuilder"
在调试过程中,我尝试了StringBuffer相反,它完美地工作。
StringBuffer对象的内容被编译为Java和Eclipse ..
On the proccess of debugging , I tried StringBuffer instead and it worked perfectly.The content of the StringBuffer object is compiled to "Java and Eclipse.."
public static void main(String[] args) {
String s = "Java";
StringBuffer strbuf = new StringBuffer(s);
change(strbuf);
System.out.println("The Stringbuffer.charAt(5) is ? " + strbuf.charAt(3));
System.out.println(strbuf);
}
private static void change(StringBuffer strbuf) {
strbuf.append(" and Eclipse");
}
}
有人可以告诉我为什么后者StringBuffer有效和Stringbuilder没有。
和是否合法将字符串传递给StringBuilder构造函数是合法的。 StringBuilder的(一个或多个);
Can someone enlighten me why the latter"StringBuffer" worked and Stringbuilder didnt. and wether or not it is legal to pass the string into the in the StringBuilder constructor. "StringBuilder(s);"
推荐答案
有一个, (它必须实现它,因为它实现了 CharSequence
)。
StringBuilder
does have a constructor accepting a String
as an argument, and does have a .charAt()
method (which it it must implement since it implements CharSequence
).
结论:这是IDE部分的一个不幸事件,它没有导入正确的的StringBuilder
。你使用另一个库,它有一个不幸的属性,它实现了一个同名的类 - 但不是在同一个包中。
Conclusion: this is a mishap from the part of your IDE, which did not import the correct StringBuilder
. You use another library which has the unfortunate "property" of having implemented a class by the same name -- but not in the same package.
去看看顶部你的文件,如果导入行是:
Go see at the top of your file if the import line is:
import java.lang.StringBuilder;
这篇关于String方法Append():StringBuilder vs StringBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!