Java开发中常见的那些坑,你踩过几个?
摘要:大家好,我是晓凡。 作为一名Java开发者,在日常编码过程中难免会遇到各种"坑"。 有些是语法层面的问题,有些则是设计或思维上的误区。 今天我们就来盘点一下Java中最常见的20个陷阱,看
大家好,我是晓凡。
作为一名Java开发者,在日常编码过程中难免会遇到各种"坑"。
有些是语法层面的问题,有些则是设计或思维上的误区。
今天我们就来盘点一下Java中最常见的20个陷阱,看看你有没有踩过这些坑。
1. == 和 equals() 混淆
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
==比较的是对象引用地址
equals()比较的是对象内容(对于String等类已重写)
2. Integer缓存陷阱
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false
Integer在-128到127之间有缓存机制,超出范围会创建新对象。
3. 字符串拼接性能问题
// 错误做法 - 性能差
String result = "";
for (int i = 0; i < 1000; i++) {
result += "a"; // 每次都创建新对象
}
// 正确做法
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("a");
}
4. 集合遍历时修改结构
// 错误做法
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
for (String item : list) {
if ("a".equals(item)) {
list.remove(item); // ConcurrentModificationException
}
}
// 正确做法
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if ("a".equals(item)) {
iterator.remove();
}
}
5. 忘记关闭资源
// 错误做法
FileInputStream fis = new FileInputStream("file.txt");
// 忘记关闭,可能导致资源泄露
// 正确做法
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 使用资源
} catch (IOException e) {
// 处理异常
}
6. 异常处理不当
// 错误做法
try {
// some code
} catch (Exception e) {
// 空的catch块,异常被默默吞掉
}
// 正确做法
try {
// some code
} catch (SpecificException e) {
logger.error("发生错误", e);
// 或者重新抛出,或者适当处理
}
7. 数组和集合的toArray()陷阱
List<String> list = Arrays.asList("a", "b");
String[] array1 = list.toArray(); // 返回Object[]
String[] array2 = list.toArray(new String[0]); // 返回String[]
不传参数的toArray()返回Object数组,不是原类型数组。
8. 泛型类型擦除
public class GenericTest<T> {
public void test() {
// T.class 是无法获取的,编译后泛型信息被擦除
}
}
运行时无法获取泛型的实际类型信息。
