开发者

How can I create a variable that will contained an unknown number of objects?

I have a procedure that recursively generates objects. The procedure takes the "last" object and generate a "new" one, the "new" object is than considered a the "last" one and so on until a "new" object cannot be generated.

I need to save all generated object. I thought to use for that an array but the problem is that I do not know in advance how many objects will be gen开发者_JAVA技巧erated (so, I cannot specify the length of the array when I declare it).

Is there a way in Java to have arrays without a fixed length? Or may be I should use not array but something else?


Go for ArrayList

List<YourClass> list = new ArrayList<YourClass>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
.
. 
.


so your code would look a bit like this:

value = something;
objects = new ArrayList();
objects.add(value);
while (true) {
    value = function(value);
    if (value == null)
        break
    objects.add(value);
}


Use a List:
http://download.oracle.com/javase/1.6/docs/api/java/util/List.html


Use an ArrayList<T>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜