我有三节课。玩家类别:

public class Player
{
private String playerName;
private int playerWorth;
private int playerSpent;
// A list of player prize objects.
private ArrayList<Prize> playerPrizeList;

public void Player()
{
     playerPrizeList = new ArrayList <Prize>();
     playerName = "";
     playerWorth = 0;
     playerSpent = 0;
}

public void playerDetails(String playerName, int playerWorth, int playerSpent)
{
    setPlayerName(playerName);
    setPlayerWorth(playerWorth);
    setPlayerSpent(playerSpent);
}

public void prize(String prizeName, int prizeWorth, int prizeCost)
{
    populatePrize(prizeName, prizeWorth, prizeCost);
}

private void populatePrize(String prizeName, int prizeWorth, int prizeCost)
{
    playerPrizeList.add(new Prize(prizeName, prizeWorth, prizeCost));
}


另一个类是PlayerList类,在该类中,我试图将一个新的播放器对象添加到可以工作的arrayList,但随后我在此Player类中还具有(Prize Objects)的priestList Array。将播放器添加到ArrayList之后,如何检索该对象并进行更改(我的最后一块代码)。我希望我能正确解释。

public class PlayerList
{
private ArrayList<Player> playerAList;

public PlayerList()
{
    playerAList = new ArrayList<Player>();
}

public ArrayList<Player> addPlayer(String playerName, int playerWorth, int playerSpent)
{
    Player newPlayer = new Player();
    newPlayer.setPlayerName(playerName);
    newPlayer.setPlayerWorth(playerWorth);
    newPlayer.setPlayerSpent(playerSpent);
    playerAList.add(newPlayer);
    return playerAList;
}

/**
 * @i is the index of ArrayList for Player Prizes
 */
public void setPlayerPrizeList(int i, String prizeName, int prizeWorth, int prizeCost)
{
    playerAList.get(i) =  currentPlayer;
    currentPlayer.populatePrize(prizeName, prizeWorth, prizeCost);
    playerAList.set(i, currentPlayer);
    return playerAList;
}

最佳答案

通常,您的方法看起来不错。

但是,您的代码中存在一些问题:


您不能将值分配给方法调用。

playerAList.get(i) =  currentPlayer;


这应该起作用,但是:

currentPlayer = playerAList.get(i);

除此之外,您不需要以下行:

playerAList.set(i, currentPlayer);


在此方法中更改的Player保留在列表中并“自动更新”,因为所有更改都在同一内存块上执行,因此已在其中创建了PlayerplayerAListcurrentPlayer保存对此存储块的引用。
还有一件事是错误的。返回类型为return的方法不能void进行任何操作:

return playerAList;





总而言之,您的方法setPlayerPrizeList()应该如下所示:

public void setPlayerPrizeList(int i, String prizeName, int prizeWorth, int prizeCost) {
    currentPlayer = playerAList.get(i);
    currentPlayer.populatePrize(prizeName, prizeWorth, prizeCost);
}

10-02 04:27