开发者

Basic question about objects and instances

I have a Class named Group, it is described as follow:

public class Group{
    public int identifier;
    public int[] members;
    public String name; 
}

Now, I wou开发者_StackOverflow社区ld like to create many different objects for this class, I mean for example 1000 groups each one has different number of members,

How can make it? I mean I would not make 1000 instructions like:

Group g1= new Group(....); 

Thanks and best regards.


You need to research arrays, and loops:

Group[] groups = new Group[1000];
for (int i = 0; i < 1000; i++) {
    groups[i] = new Group();
    groups[i].identifier = XXX;
    groups[i].members    = new int[XXX];
    ...
}


Can you not use an array and a loop? E.g.:

...
public static final int ARRAY_SIZE = 1000;
...
Group arr[] = new Group[ARRAY_SIZE];
for( int i = 0; i < arr.size; i++ ) {
 arr[i] = new Group();
}


If you want to assign different values to each of the 100 instances, then yes, you are facing a lot of typing. You can create the objects in a loop ( as Oli describes ), but to assign the different values you'll still end up doing

groups[0].identifier = 10;
groups[1].identifier = 44;
groups[3].identifier = 99;

etc etc.

You may be able to put the parameters in a file and wirte code to read the file and set the values in your object instances, but one way or another, unless the parameters can be generated by algorithm, you're going to end up typing them in

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜