[Android] One reason why the object is null: Inside the method, a new object is recreated and assigned to the original object, but this does not change the reference of the original original object

doubt

Now have the code as follows:

private GameList multiGameList;

/**
 * 获取多人游戏列表
 *
 * @return 多人游戏列表
 */
public GameList getMultiGameList() {
    
    
    if (null == multiGameList) {
    
    
        createMultiOrSingleGameList(multiGameList,GameList.TYPE_MULTI);
    }
    return multiGameList;
}

/**
 * 创建多人或者单人游戏列表
 * @param gameList 游戏列表容器
 * @param type 游戏类型,1为单人,2为多人
 */
private void createMultiOrSingleGameList(GameList gameList, int type) {
    
    
    gameList = new GameList();
    for (GameList.Game game : bizGameList.getList()) {
    
    
        // 当为多人或者单人游戏的时候整理到游戏列表中
        if (game.getGameType() == type) {
    
    
            gameList.getList().add(game);
        }
    }
}

Why is the object I got by calling the getMultiGameList() method in other classes still null? What’s wrong with writing this way? Why? How to avoid it?

answer

The problem is in the createMultiOrSingleGameList method, the gameList parameter you pass is a reference to an object. Inside the method, you recreate a new GameList object and assign it to gameList, but this does not change the reference to the original multiGameList object.

To fix this, you can modify the createMultiOrSingleGameList method so that it returns a new GameList object instead of modifying it with parameters. Then in the getMultiGameList method, assign the returned new object to multiGameList.

The modified code looks like this:

private GameList multiGameList;

/**
 * 获取多人游戏列表
 *
 *  多人游戏列表
 */
public GameList getMultiGameList() {
    
    
    if (null == multiGameList) {
    
    
        multiGameList = createMultiOrSingleGameList(GameList.TYPE_MULTI);
    }
    return multiGameList;
}

/**
 * 创建多人或者单人游戏列表
 *  type 游戏类型,1为单人,2为多人
 */
private GameList createMultiOrSingleGameList(int type) {
    
    
    GameList gameList = new GameList();
    for (GameList.Game game : bizGameList.getList()) {
    
    
        // 当为多人或者单人游戏的时候整理到游戏列表中
        if (game.getGameType() == type) {
    
    
            gameList.getList().add(game);
        }
    }
    return gameList;
}

After this modification, calling the getMultiGameList method will return the correct multiGameList object instead of null.

Guess you like

Origin blog.csdn.net/weixin_44002043/article/details/131901883