1、字符串连接误用
错误的写法:
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 bufferfor (Person p : persons) {
if (sb.length() > 0) sb.append(", ");
sb.append(p.getName);
}
2、数字转换成字符串
错误的写法:
“” + set.size()
new Integer(set.size()).toString()
正确的写法:
String.valueOf(set.size())
3、将 Array 转换成 ArrayList 时出错
错误的写法:
List list = Arrays.asList(arr);
正确的写法:
ArrayList arrayList = new ArrayList(Arrays.asList(arr));
4、检查 array 里是否含有某个值时出错
错误的写法:
Set set = new HashSet(Arrays.asList(arr));
return set.contains(targetValue);
正确的写法:Arrays.asList(arr).contains(targetValue);
5、错误的使用StringBuffer
错误的写法;
StringBuffer sb = new StringBuffer();
sb.append(“Name: “);
sb.append(name + ‘\n’);
sb.append(”!”);
…
String s = sb.toString();
正确的写法:
StringBuilder sb = new StringBuilder(100);
sb.append(“Name: “);
sb.append(name);
sb.append(”\n!”); String s = sb.toString();
6、遍历 list 移除元素时出错
错误的写法:
ArrayList list = new ArrayList(Arrays.asList(“a”, “b”, “c”, “d”));
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
正确的写法
:ArrayList list = new ArrayList(Arrays.asList(“a”, “b”, “c”, “d”));
Iterator iter = list.iterator();
while (iter.hasNext()) {
String s = iter.next();
if (s.equals(“a”)) {
iter.remove();
}
}
7、利用不可变对象(Immutable)
错误的写法:
zero = new Integer(0); return Boolean.valueOf(“true”);
zero = Integer.valueOf(0); return Boolean.TRUE;
正确的写法:
zero = Integer.valueOf(0); return Boolean.TRUE;
8、未对数据流进行缓存
错误的写法:
nputStream in = new FileInputStream(file); int b; while ((b = in.read()) != -1) {
…
}
正确的写法:
InputStream in = new BufferedInputStream(new FileInputStream(file));
熟能生巧,只有多去练习,多去打码,才不会容易犯错,Java的世界还很大很广,这需要你去不断探索,不断进步!