I've a question about singleton class. When I call method next(), I expect that mProcessIndex will be increased but in reality, it won't so it causes stackoverflow error. So, the question is what is correct way to modify mProcessIndex value?
Code below :
public class HomePopupDisplayManager {
private static HomePopupDisplayManager sInstance;
private List<WeakReference<HomePopupMessage>> mMessages;
private int mProcessIndex;
private HomePopupDisplayManager() {
mMessages = new ArrayList<>();
mProcessIndex = 0;
}
public static synchronized HomePopupDisplayManager getInstance() {
if (sInstance == null) {
sInstance = new HomePopupDisplayManager();
}
return sInstance;
}
public void register(@NonNull HomePopupMessage message, @IntRange(from = 0) int order) {
mMessages.add(order, new WeakReference<>(message));
}
public void next() {
if (mProcessIndex >= 0 && mProcessIndex < mMessages.size()) {
HomePopupMessage message = mMessages.get(mProcessIndex).get();
if (message != null) {
next();
mProcessIndex++;
}
}
}
}
The problem is in :
next();
mProcessIndex++;
Should be:
mProcessIndex++;
next();
您的next()函数进入无限递归循环,因为在递增mProcessIndex之前调用了该函数。因此mProcessIndex永远不会递增。 在next()之前调用mProcessIndex ++ ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.