String s = "";
for (Person p : persons) {
s += ", " + p.getName();
}
s = s.substring(2); //remove first comma
正确的写法:
StringBuilder sb = new StringBuilder(persons.size() * 16); // well estimated buffer
for (Person p : persons) {
if (sb.length() > 0) sb.append(", ");
sb.append(p.getName);
}
错误的使用StringBuffer
错误的写法:
StringBuffer sb = new StringBuffer();
sb.append("Name: ");
sb.append(name + '\n');
sb.append("!");
...
String s = sb.toString();
if ("John".equals(name)) ...
if (name.length() == 0) ...
if (name.isEmpty()) ...
数字转换成字符串
错误的写法:
"" + set.size()
new Integer(set.size()).toString()
正确的写法:
String.valueOf(set.size())
利用不可变对象(Immutable)
错误的写法:
zero = new Integer(0);
return Boolean.valueOf("true");
正确的写法:
zero = Integer.valueOf(0);
return Boolean.TRUE;
请使用XML解析器
错误的写法:
int start = xml.indexOf("<name>") + "<name>".length();
int end = xml.indexOf("</name>");
String name = xml.substring(start, end);
正确的写法:
SAXBuilder builder = new SAXBuilder(false);
Document doc = doc = builder.build(new StringReader(xml));
String name = doc.getRootElement().getChild("name").getText();
请使用JDom组装XML
错误的写法:
String name = ...
String attribute = ...
String xml = "<root>"
+"<name att=\""+ attribute +"\">"+ name +"</name>"
+"</root>";
正确的写法:
Element root = new Element("root");
root.setAttribute("att", attribute);
root.setText(name);
Document doc = new Documet();
doc.setRootElement(root);
XmlOutputter out = new XmlOutputter(Format.getPrettyFormat());
String xml = out.outputString(root);
Reader r = new FileReader(file);
Writer w = new FileWriter(file);
Reader r = new InputStreamReader(inputStream);
Writer w = new OutputStreamWriter(outputStream);
String s = new String(byteArray); // byteArray is a byte[]
byte[] a = string.getBytes();
这样的代码主要不具有跨平台可移植性。因为不同的平台可能使用的是不同的默认字符编码。
正确的写法:
Reader r = new InputStreamReader(new FileInputStream(file), "ISO-8859-1");
Writer w = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1");
Reader r = new InputStreamReader(inputStream, "UTF-8");
Writer w = new OutputStreamWriter(outputStream, "UTF-8");
String s = new String(byteArray, "ASCII");
byte[] a = string.getBytes("ASCII");
未对数据流进行缓存
错误的写法:
InputStream in = new FileInputStream(file);
int b;
while ((b = in.read()) != -1) {
...
}
Socket socket = ...
socket.connect(remote, 20000); // fail after 20s
InputStream in = socket.getInputStream();
socket.setSoTimeout(15000);
int i = in.read();