Java进行循环创建对象的n个量 [英] Java for loop to create n amount of object

查看:140
本文介绍了Java进行循环创建对象的n个量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助。我想创建一个for循环,创建一个类,对象的n个,然后将其添加到一个ArrayList。事情是这样的:

  //播放器是一个自定义类
ArrayList的<玩家GT; numberofPlayersArray;
numberofPlayersArray =新的ArrayList<播放器及GT;();// n是,我想创建Player类对象的数量变量
  的for(int i = 0; I< N;我++)
  {    //这是我能想出但我失去了一些东西     玩家P;
     P =新播放器
     numberofPlayersArray.add(P);    }

任何帮助将AP preciated


解决方案

  //播放器是一个自定义类
ArrayList的<玩家GT; numberofPlayersArray =新的ArrayList<播放器及GT;(N);// n是,我想创建Player类对象的数量变量
的for(int i = 0; I< N;我++){    //这是我能想出但我失去了一些东西     玩家P =新的球员();
     numberofPlayersArray.add(P);
}

请注意,这是更好地初始化的ArrayList 的大小,如果它是已知的(如你的情况)

I need some help. I want to create a for loop that creates n number of objects of a class, and then adds them into an arraylist. Something like this:

//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);

    }

Any help would be appreciated

解决方案

//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++) {

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

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

Note that it's better to initialize the ArrayList with the size, if it is known (as in your case)

这篇关于Java进行循环创建对象的n个量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆