2012-04-29 45 views
-1

我希望能够访问在一个for循环对象如下:使用变量来访问多个对象

for (int i=0; i<5: i++) 
{ object[i].doSomething(); } 

但是围绕object[i]部分的语法脱离了我。

+0

http://www.oopweb.com/Java/Documents/ThinkCSJav/Volume/chap11.htm – 2012-04-29 02:20:31

+0

本雅明的答案是一个很好的。但是,如果'object'确实是对象,那么你应该知道这个代码根本不起作用。此语法用于以类C语法(Java,C++,Javascript等)访问数组的元素。如果'object'是一个ArrayList,那么你会想要做'object.get(i)'。 – Hassan 2012-04-29 02:44:00

回答

2
for (  // loop 
int i = 0; // initialize the variable i before starting to iterate 
i < 5;  // perform the block below while i < 5 
i ++)  // increment i after performing the block below 
{      // start of block to execute in each iteration of the for-loop 
    object[i]   // the i-th element of the array object 
    .doSomthing();  // call this method on ^^ 
}      // end block 

很好的参考: