我有一个容器,可以在几个屏幕大小的窗格之间切换其主要内容。我没有使用CardLayout
,而是使用remove(previous); add(current); validate();
在这个容器中,我有每个窗格的数据字段,这些窗格在启动时初始化,这样我就可以轻松地在它们之间切换引用。
我的问题:
如果删除上一个窗格并添加新的/当前窗格,前一个窗格的实例对象占用的内存是否仍保留在内存中?
因为我考虑将前一个窗格设置为null并重新创建当前窗格,然后再将其添加到容器中以尝试降低内存使用量,但不确定它是否会实际产生任何差异。
感谢。 :)
编辑:这实际上不是我的课程,但它展示了我如何切换视图:
public class ViewManager {
public static final int VIEW_LOGIN = 0;
public static final int VIEW_CALENDAR = 1;
public static final int VIEW_HELP = 2;
public static final int VIEW_SETTINGS = 3;
public static final int VIEW_PREFERENCES = 4;
public static final int VIEW_STATS = 5;
private static LoginPane login = new LoginPane();
private static CalendarView calendar = new CalendarView();
private static HelpPane help = new HelpPane();
private static SettingsPane accountSettings = new SettingsPane();
private static PreferencesPane preferences = new PreferencesPane();
private static StatsPane stats = new StatsPane();
private static int previousView;
private static Object [] views = {login, calendar, help, accountSettings, preferences, stats};
// Without settings old views to null and re-creating incoming view request
public static void switchTo(int currentView){
if(currentView == previousView) return;
MainFrame.getContent().remove(views[previousView]);
MainFrame.getContent().add(views[currentView]);
MainFrame.getContent().validate();
}
// Settings to null and re-creating incoming view request
public static void switchToNullify(int currentView){
if(currentView == previousView) return;
MainFrame.getContent().remove(views[previousView]);
views[previousView] = null;
if(currentView == VIEW_LOGIN) views[VIEW_LOGIN] = new LoginPane();
else if(currentView == VIEW_CALENDAR) views[VIEW_CALENDAR] = new CalendarView();
else if(currentView == VIEW_HELP) views[VIEW_HELP] = new HelpPane();
else if(currentView == VIEW_SETTINGS) views[VIEW_ACCOUNT_SETTINGS] = new SettingsPane();
else if(currentView == VIEW_PREFERENCES) views[VIEW_PREFERENCES] = new PreferencesPane();
else if(currentView == VIEW_STATS) views[VIEW_STATS] = new StatsPane();
MainFrame.getContent().add(views[currentView]);
MainFrame.getContent().validate();
}
}
答案 0 :(得分:3)
如果您删除上一个窗格并添加新的/当前窗格,那么 前一个窗格的实例对象占用的内存仍然存在 存储器?
是的,除非您删除对该对象的所有引用。一旦你完成了它,它就有资格进行垃圾收集。
因为我考虑将上一个窗格设置为
null
...
好主意!