0

我有这样的情况

String[] ids = new String[depts.size()];
for (int i=0; i<ids.length; i++)
{
  ids [i] = ("Dept" + .... )
}

因此,循环查看长度设置为 depts.size 的 id。但我需要向 ids [i] 添加另一个字符串项,例如“Region”+ reg_num。就像 ids[i] 中的下一项必须是“Region”+ reg_num 并且每个部门都重复此操作。
由于它是由长度控制的,我该怎么做?如何调整循环以增加 1 个项目。任何建议将不胜感激。

谢谢。

4

4 回答 4

3

只需使用 aList而不是数组。与数组不同,列表可以动态调整大小:

final List<String> newList = new ArrayList<>(oldList);
newList.add(newElement);

编辑如果您仍在使用 Java 6,则必须:

final List<String> newList = new ArrayList<String>(oldList);

反而

EDIT 2根据您的用例,您甚至可能不需要第二个列表;由于列表可以动态调整大小,除非您绝对需要复制它,否则只需保留相同的列表:

// first call
list.add(something);
// second call
list.add(somethingElse);
// etc etc

但是,如果没有看到更多代码,就很难说。

于 2013-06-11T15:42:31.173 回答
1

如果您事先知道,则相应地初始化数组并将元素添加为:

   String[] ids = new String[depts.size()+1];//added one in the length
   for (int i=0; i<ids.length; i++)
   {
     ids [i] = ("Dept" + .... )
   }
   ids[ids.length-1] = "Region"+....; 

或者

   String[] ids = new String[2*depts.size()];//added one in the length
   for (int i=0; i<ids.length; i=i+2)
   {
     ids [i] = ("Dept" + .... )
     ids[i+1] = "Region"+....; 
   }
于 2013-06-11T15:45:23.513 回答
1

如果您尝试为每个 id 存储一个部门,那么最好定义一个这样的自定义类:

public class Region {
    String id;
    String dept;
    public Region(String id, String dept) {
        this.id=id;
        this.dept=dept;
    }
    // getters for id and dept
}

then define your region array like this

Region[] regions = new Region[depts.size()];
for (int i=0; i<regions.length; i++) {
  regions[i] = new Region("Dept"+i, "Region"+i);
}
于 2013-06-11T15:49:21.020 回答
0

如果我正确理解了您的要求,您可以执行以下操作(但请记住,您可以保存字符串列表而不是数组,以动态更改它):

String[] ids = new String[depts.size()*2];
for (int i=0; i<ids.length; i+=2)
{
  // depts index would be i/2
  ids [i] = ("Dept" + .... )
  ids[i+1] = "Region"; // + ...
}
于 2013-06-11T15:45:05.397 回答