过时的引用和内存不足错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过时的引用和内存不足错误相关的知识,希望对你有一定的参考价值。

为什么version4方法抛出内存错误,但version3方法不抛出它,我认为在这两种情况下都存在问题是“过时参考”?

private static void version4() {
    int count = 0;
    long start = System.nanoTime();
    try {
        List<Calendar> list = new ArrayList<>();
        System.out.println(list.size());
        while(true){
            for (int i = 0; i < 1000; i++) {
                Calendar calendar = Calendar.getInstance();
                list.add(i, calendar);
            }
        }
    } catch (Error e) {
        e.printStackTrace();
    }
    long end = System.nanoTime();
    System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}

private static void version3() {
    int count = 0;
    long start = System.nanoTime();
    try {
        Calendar[] calendars = new Calendar[1000]; 
        while(true){
            for (int i = 0; i < calendars.length; i++) {
                Calendar calendar = Calendar.getInstance();
                calendars[i] = calendar;
            }
        }
    } catch (Error e) {
        e.printStackTrace();
    }
    long end = System.nanoTime();
    System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}
答案

在这两种情况下,由于外部while (true),你永远循环。 但是在数组的情况下,在内部循环中,您将覆盖数组的旧值(长度为1000)。所以内存消耗大致不变。 在ArrayList的情况下,你在内循环中添加新的Calendar对象。因此内存使用量不断增长:1000(第一次循环)+ 1000次(第二次循环)+ ...

以上是关于过时的引用和内存不足错误的主要内容,如果未能解决你的问题,请参考以下文章