是否可以使用for循环在Java中创建n个对象? [英] Is it possible to create n number of objects in java using a for loop?
本文介绍了是否可以使用for循环在Java中创建n个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如;我正在使用此类:
For example; i'm using this class:
Point originOne = new Point(x, y);
如果我要创建N个点(originTwo,originThree ... originN); 我可以使用像这样的for循环吗?
If i want to create a N number of points (originTwo,originThree...originN); can I do it using a for loop like :
for(int i=0;i<n-1;i++){
}
如果可能的话;我如何给他们起不同的名字?
If it's possible; how do i give them different names?
推荐答案
您可以将它们放入数组中.
You could put them into an array.
Point[] origin = new Point[n];
for (int i = 0; i < n; i++) {
origin[i] = new Point(x, y);
}
在这些情况下,他们都将使用相同的x
和y
.
They'd all be using the same x
and y
under those conditions.
如果您有一个x
和y
的数组,则可以这样操作:
If you had an array of x
and y
you could do it like this:
Point[] origin = new Point[n];
for (int i = 0; i < n; i++) {
origin[i] = new Point(x[i], y[i]);
}
如果您不喜欢数组,则可以使用列表:
If you don't like arrays, you could use a list:
List<Point> origin = new ArrayList<>();
for (int i = 0; i < n; i++) {
origin.add(Point(x[i], y[i]));
}
您将其称呼为
origin.get(i)
这篇关于是否可以使用for循环在Java中创建n个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文