我有两个日历实例变量,一个全局声明,另一个在本地声明。现在假设我将一个日历实例分配给另一个像
Calendar m_CalGlobally = Calendar.getInstance();
Calendar calLocally = m_CalGlobally;
现在我的问题是,如果我对 calLocally 变量进行任何更改,相同的更改会出现在 m_CalGlobally 实例变量中,为什么会发生这种情况,以及分配它的方法是什么。
这绝对行不通。这样做
Calendar m_CalGlobally = Calendar.getInstance();
Calendar calLocally = (Calendar)m_CalGlobally.clone(); // Proper way to assign this.
//This will give you calender with same properties and also the changes of it wont be reflected on m_CalGlobally because assigning with equal operator make them point to same reference.
那是因为m_CalGlobally
和calLocally
都是对相同(相同)对象的引用。要让它们独立,您需要创建另一个日历实例。Calendar calLocally = m_CalGlobally;
假设您在第 2 行 ( )中有错字