【问题标题】:Quick Java garbage collection question快速Java垃圾收集问题
【发布时间】:2011-08-06 18:49:47
【问题描述】:

我正在用 Android 编写一个闹钟应用程序,我有以下内容:

ArrayList<PendingIntent> pendingIntents = new ArrayList<PendingIntent>();

public PendingIntent setAlarm(long time) {
    ...other code.
    PendingIntent pi = PendingIntent.getBroadcast(context, num, intent, flags);
    return pi;
}

我想知道如果在下面多次执行此操作,是否每次都会覆盖原始的 Pending Intent 引用?

pendingIntents.add(num, setAlarm(1000));

【问题讨论】:

    标签: java collections reference garbage


    【解决方案1】:

    没有

    基本上,您暂时将对象引用分配给变量pi。变量被覆盖,但对象未被覆盖。它会安全地添加到您的列表中以供将来使用。

    【讨论】:

    • 我就是这么想的。谢谢!
    • @thomas farrell,很高兴它有帮助。如果此答案解决了您的问题,请通过单击此答案旁边的向上勾号将其标记为已回答。 See here how.
    【解决方案2】:

    不,不是。

    每次调用add 时,都会在指定索引之后插入一个元素。

    也许您打算使用set。那个替换了 num 位置的项目,旧值符合 GC 条件。

    【讨论】:

    • 不。我想确保在堆上创建的对象都是单独的对象,我的数组列表中的每个对象都指向每个单独的对象。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2014-03-31
    • 2010-12-13
    • 2011-02-23
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多