问题
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