Is it possible to create n number of objects in java using a for loop? [duplicate]

一曲冷凌霜 提交于 2020-01-11 07:11:09

问题


For example; i'm using this class:

Point originOne = new Point(x, y);

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?


回答1:


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

They'd all be using the same x and y under those conditions.

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]));
}

You'd address them as

origin.get(i)



回答2:


This will also work if your point will be same, else mastov's solution.

Point[] origin = new Point[n]; Arrays.fill(origin, new Point(x,y));



来源:https://stackoverflow.com/questions/32597399/is-it-possible-to-create-n-number-of-objects-in-java-using-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!