Java

Java语法糖

2021-10-21  本文已影响0人  TZX_0710

try-wit-resources

关闭资源的常用方式就是在finally块里释放,即调用close方法。比如,我们经常会写这样的代码:

public static void main(String args[]) {
    BufferedReader br = null;
    try {
        String line;
        br = new BufferedReader(new FileReader("d:\\hello.xml"));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        // handle exception
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            // handle exception
        }
    }
}

从Java 7开始,jdk提供了一种更好的方式关闭资源,使用try-with-resources语句,改写一下上面的代码,效果如下:

public static void main(String args[]) {
    try (BufferedReader br = new BufferedReader(new FileReader("d:\\ hello.xml"))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        // handle exception
    }
}
//反编译后
try (BufferedReader br = new BufferedReader(new FileReader("d:\\ hello.xml"))) {
    is.read();
    ...
} catch(Exception e) {
    ...
} finally {
    //no need to add code to close InputStream, its close method will be internally called
    //(无需添加关闭InputStream输入流的代码,其close()方法会自行调用)
}

增加for循环

for (Student stu : students) {    
    if (stu.getId() == 2) {
        students.remove(stu);  
    }           
}
会抛出ConcurrentModificationException异常。

Iterator是工作在一个独立的线程中,并且拥有一个 mutex 锁。
Iterator被创建之后会建立一个指向原来对象的单链索引表
当原来的对象数量发生变化时,这个索引表的内容不会同步改变,
所以当索引指针往后移动的时候就找不到要迭代的对象,
所以按照fail-fast 原则Iterator 会马上抛出java.util.ConcurrentModificationException异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。
但你可以使用 Iterator 本身的方法remove()来删除对象,
Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性

上一篇下一篇

猜你喜欢

热点阅读