【问题标题】:Calling methods on like objects in a loop [closed]在循环中调用类似对象的方法[关闭]
【发布时间】:2014-05-21 01:02:12
【问题描述】:

假设我有 4 个对象:

  • stringItem1
  • stringItem2
  • stringItem3
  • stringItem4

我想使用一种由它们各自实现的方法,称为setText(String argument)。我想知道是否可以使用循环为每个对象调用该方法。与其说对象的编号(stringItem1stringItem4),不如让 for 循环来做,像这样:

for(int x=1; x<=4; x++){    
    stringItemx.setText("LOL");
}

【问题讨论】:

  • 你要调查Arrays
  • 为什么这个问题值得一票否决?请发表评论。
  • 这是不可理解的。这没有意义。术语有误:问题显示出对多个技术术语的根本误解。

标签: java for-loop


【解决方案1】:

是的,如果你把它们放在一个数组中。 像这样:

StringItem[] items = new StringItem[4];
items[0] = stringItem1;
//etc...
for(int i=0; i < 4; i++){
   items[i].setText("LOL");
}

【讨论】:

    【解决方案2】:

    您可以声明一个字符串项目对象的数组,然后您可以通过它们的索引来引用它们。

    JTextField[] stringItems = {stringItem1, stringItem2, /* ... */, stringItem10};
    

    稍后,您可以使用for 循环。

    for (int i = 0; i < stringItems.length; i++) {
        stringItems[i].setText("LOL");
    }
    

    【讨论】:

      【解决方案3】:

      不,这不可能。

      相反,您可以将数据存储在Map&lt;String, YourObject&gt; 中,使用变量的名称 作为键,并使用键从Map 中检索元素以应用值:

      Map<String, YourObject> map = new HashMap<>();
      map.put("stringItem1", stringItem1);
      map.put("stringItem2", stringItem2);
      //...
      map.put("stringItem10", stringItem10);
      for(int x=1;x<=10;x++){
          map.get("stringItem" + x).setText("LOL");
      }
      

      【讨论】:

        【解决方案4】:

        不,因为stringItemx 未在此上下文中声明。你会得到一个错误。

        您可以考虑在这 4 个对象之间使用其他参数或其他相似性。因为这行不通。

        【讨论】:

          【解决方案5】:

          没有。您必须为您的对象创建一个数组,并且您可以通过解析数组来遍历每个对象。

          【讨论】:

            猜你喜欢
            • 2013-06-22
            • 1970-01-01
            • 1970-01-01
            • 2017-02-26
            • 1970-01-01
            • 1970-01-01
            • 2021-08-31
            • 2021-12-10
            • 1970-01-01
            相关资源
            最近更新 更多