gpt4 book ai didi

Java for循环创建n个对象

转载 作者:行者123 更新时间:2023-12-04 20:01:00 26 4
gpt4 key购买 nike

我需要一些帮助。我想创建一个 for 循环来创建一个类的 n 个对象,然后将它们添加到一个数组列表中。像这样的:

//Player is a custom class 
ArrayList<Player> numberofPlayersArray;
numberofPlayersArray = new ArrayList<Player>();

//n is a variable for the number of Player class objects that I want to create
for(int i = 0; i < n; i++)
{

//this is what I can come up with but I am missing something

Player p;
p = new Player
numberofPlayersArray.add(p);

}

任何帮助将不胜感激

最佳答案

//Player is a custom class 
ArrayList<Player> numberofPlayersArray = new ArrayList<Player>(n);

//n is a variable for the number of Player class objects that I want to create
for(int i = 0; i < n; i++) {

Player p = new Player();
numberofPlayersArray.add(p);
}

请注意,最好用大小初始化 ArrayList,如果它是已知的(如您的情况)

关于Java for循环创建n个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1815955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com