【问题标题】:Use variable to access multiple objects使用变量访问多个对象
【发布时间】:2012-04-29 02:15:33
【问题描述】:

我希望能够在 for 循环中访问对象,如下所示:

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

但是object[i] 部分的语法让我无法理解。

【问题讨论】:

  • Binyamin 的回答很好。但是,您应该知道,如果 object 确实是对象,则此代码根本不起作用。此语法用于以类 C 语法(Java、C++、Javascript 等)访问数组元素。如果 object 是一个 ArrayList,那么你会想要做 object.get(i)。

标签: java variables for-loop


【解决方案1】:
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

很好的参考:

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2015-07-09
    • 2011-06-10
    • 2014-08-20
    • 2015-09-23
    相关资源
    最近更新 更多