有没有更有效的编码方式?

Is there a more efficient way to code this?

    final Icon[] landIcons = {
        /* for(int i=0, i<15, i++)
          {
             new ImageIcon(getClass().getResource(landNames[i]));
          }
      }*/
       new ImageIcon(getClass().getResource(landNames[0])),
       new ImageIcon(getClass().getResource(landNames[1])),
       new ImageIcon(getClass().getResource(landNames[2])),
       new ImageIcon(getClass().getResource(landNames[3])),
       new ImageIcon(getClass().getResource(landNames[4])),
       new ImageIcon(getClass().getResource(landNames[5])),
       new ImageIcon(getClass().getResource(landNames[6])),
       new ImageIcon(getClass().getResource(landNames[7])),
       new ImageIcon(getClass().getResource(landNames[8])),
       new ImageIcon(getClass().getResource(landNames[9])),
       new ImageIcon(getClass().getResource(landNames[10])),
       new ImageIcon(getClass().getResource(landNames[11])),
       new ImageIcon(getClass().getResource(landNames[12])),
       new ImageIcon(getClass().getResource(landNames[13])),
       new ImageIcon(getClass().getResource(landNames[14]))};

我创建了一个图标数组,并在注释中提出了循环每个元素的想法。我不能说为什么它不能以这种方式在 for 循环中工作。还有另一种方法可以缩短所有这些代码吗?谢谢!

它不起作用,因为它是非法语法。

final Icon[] landIcons = {
        for(int i=0, i<15, i++)
          {
             new ImageIcon(getClass().getResource(landNames[i]));
          }
      }

你不能运行在数组初始化块中循环

使用这个:

  final Icon[] landIcons = new Icon[15];
  for(int i=0, i<landIcons.length , i++)
    {
       landIcons[i] = new ImageIcon(getClass().getResource(landNames[i]));
    }

您可以使用列表来保存项目,以便您可以使用循环将 ImageIcon 添加到该列表。如果您确实需要一个数组,请在该列表上调用 toArray()。