我有三节课。玩家类:
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类中也有一个prizeList数组(Prize Objects)。一旦我将播放器添加到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;
}
答案 0 :(得分:1)
一般来说,您的方法看起来不错。
但您的代码中存在一些问题:
您无法为方法调用指定值。
playerAList.get(i) = currentPlayer;
但这应该有效:
currentPlayer = playerAList.get(i);
除此之外,您不需要这一行:
playerAList.set(i, currentPlayer);
此方法中您要更改的Player
会保留在列表中并自动更新&#34;,因为所有更改都在同一个内存块上执行,{{1}已经创建了。Player
和playerAList
都拥有对此内存块的引用。
还有一件事是错的。您无法currentPlayer
来自返回类型为return
的方法的任何内容:
void
总而言之,您的方法return playerAList;
应如下所示:
setPlayerPrizeList()