0

I want to make n instance of one class and manipulate its variables. For example I have Class A that contain variables and i have n instance of this class with b as an object and c as variable d as value

    A b_1 = new A()
    A b_2 = new A()
    A b_n = new A()

I want to make a loop that do this:

    for ( int i=1; i<n; i++) {
        b_n.c =d 
    }
4

2 回答 2

2

你想要一个数组。创建一个大小为 的数组n

A objects = new A[n];

遍历数组,初始化对对象的每个引用,并设置变量。

for (int i = 0; i < objects.length; ++i) {
    objects[i] = new A();
    objects[i].setC(b);
}

顺便说一句,您应该public为 field 创建一个 getter c,而不是直接访问它。并作场private

于 2013-10-02T15:32:28.980 回答
1

您应该使用数组或 A 的集合。

列表示例:

List<A> myAs = new ArrayList<A>();
myAs.add(new A());
...

for(A a: myAs) {
 a.doSomething()
}
于 2013-10-02T15:34:09.107 回答