在Debian上使用Java时,有一些常见的误区需要注意。以下是一些典型的例子:
if (str == "hello") { ... }
使用 ==
比较字符串会导致比较的是对象的引用,而不是字符串的内容。if ("hello".equals(str)) { ... }
或者使用 Objects.equals(str, "hello")
来避免空指针异常(NPE)。List<String> list = new ArrayList<>();
for (String item : list) {
if (item.equals("remove")) {
list.remove(item); // 可能抛出ConcurrentModificationException
}
}
在遍历集合时直接修改集合会导致 ConcurrentModificationException
。Iterator
:Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("remove")) {
it.remove();
}
}
removeIf
(Java 8+):list.removeIf(item -> item.equals("remove"));
Date date = new Date();
date.setDate(date.getDate() + 1); // 使用过时的方法
使用过时的 Date
类的方法进行日期计算。LocalDate
:LocalDate date = LocalDate.now();
date = date.plusDays(1);
Calendar
类:Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
FileInputStream fis = new FileInputStream("file.txt");
// 没有关闭流
未正确关闭资源可能导致资源泄漏。try-with-resources
语句自动关闭资源:try (FileInputStream fis = new FileInputStream("file.txt")) {
// 使用资源
} catch (IOException e) {
e.printStackTrace();
}
List<fruit> plate = new ArrayList<apple>();
这会导致类型不兼容的错误,因为 ArrayList<apple>
不能转换为 List<fruit>
。? extends fruit
:List<? extends fruit> plate = new ArrayList<apple>();
这表示 plate
可以引用任何继承自 fruit
的子类型的列表。export JAVA_HOME=/usr/local/jdk-1.6.0_16
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib
设置环境变量时,路径和类路径的格式不正确。export JAVA_HOME=/usr/local/jdk-1.6.0_16
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib
希望这些常见的误区能帮助你更好地在Debian上使用Java。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:Debian清理有哪些误区