避开Java开发中常见的“隐形陷阱”
日常Java开发中,有些细节看似微小,却能大幅影响代码质量。分享三个实用技巧,助你写出更健壮的代码。
1. 集合遍历时删除元素,用对方法了吗?
很多新手会这样写:
for (String str : list) {
if (str.equals("test")) {
list.remove(str); // 抛出ConcurrentModificationException
}
}
正确做法是使用迭代器的remove()方法,或直接使用Collection.removeIf()(JDK8+):
list.removeIf(str -> str.equals("test"));
2. Optional类,优雅解决空指针
不要这样:
if (user != null) {
Address address = user.getAddress();
if (address != null) {
String city = address.getCity();
// ...
}
}
请这样写:
Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.ifPresent(city -> // ...);
3. 字符串拼接,请记住性能
循环中拼接字符串,请用StringBuilder而非“+”。但更推荐使用String.join()或Collectors.joining():
List<String> list = Arrays.asList("a", "b", "c");
String result = String.join(", ", list); // a, b, c
这些技巧虽小,但能让代码更简洁、健壮。你有遇到过哪些Java开发的坑?欢迎分享交流。