Java 向循环中的数组添加值

Java 向循环中的数组添加值,java,arrays,arraylist,Java,Arrays,Arraylist,在我的程序中,我试图在数组循环时向数组添加值。在将其放入数组之前,它必须完成if语句。我需要能够根据输入添加所需数量的值。我不知道该怎么做。任何帮助都将不胜感激 for(int a=0; a<= subset1white.length-1;a++){ String w = Integer.toString(Integer.parseInt(subset1white[a]) + 2); String x = Integer.toString(Integer.parseInt(subs

在我的程序中,我试图在数组循环时向数组添加值。在将其放入数组之前,它必须完成if语句。我需要能够根据输入添加所需数量的值。我不知道该怎么做。任何帮助都将不胜感激

for(int a=0; a<= subset1white.length-1;a++){
  String w = Integer.toString(Integer.parseInt(subset1white[a]) + 2);
  String x = Integer.toString(Integer.parseInt(subset1white[a]) - 2);
  String y = Integer.toString(Integer.parseInt(subset1white[a]) + 10);
  String z = Integer.toString(Integer.parseInt(subset1white[a]) - 10);
  String[] arithmetic = {w, x, y, z};
     for(int b=0; b<= arithmetic.length-1; b++){
        if(arithmetic[b] == subset1black[a]){

        }
     }

  }
for(int a=0;a使用
ArrayList
,它可以根据需要动态增长(如以下建议):

//声明
列表结果=新建ArrayList();
//添加到列表的末尾
结果。添加(第1部分黑色[a]);
有关更多信息,或者如果要以其他方式将元素添加到列表中,请参见


如果您确实需要一个基元数组,您可以转换
列表。请参见此。

Java中没有可变大小的基元数组,因此最接近这种数据结构的是
ArrayList
类,它在内部是一个对象数组,必要时可以调整大小。它有助于将
ArrayList
初始化为预期的大小(或更大一点),以避免调整大小,但这种优化是没有必要的

对于上述代码,上述代码的实现可以是:

List<Integer> result = new ArrayList<Integer>(subset1white.length);

for (int a=0; a<subset1white.length; a++) {

  String w = Integer.toString(Integer.parseInt(subset1white[a]) + 2);
  String x = Integer.toString(Integer.parseInt(subset1white[a]) - 2);
  String y = Integer.toString(Integer.parseInt(subset1white[a]) + 10);
  String z = Integer.toString(Integer.parseInt(subset1white[a]) - 10);

  String[] arithmetic = {w, x, y, z};

  for (int b=0; b<= arithmetic.length-1; b++) {
    if (arithmetic[b] == subset1black[a]) {
      result.add(new Integer(subset1black[a]));
    }
  }    
}
List result=new ArrayList(subset1white.length);

对于(int a=0;a为什么不使用
ArrayList
?它就像一个可以在需要时动态增长的数组。
List<Integer> result = new ArrayList<Integer>(subset1white.length);

for (int a=0; a<subset1white.length; a++) {

  String w = Integer.toString(Integer.parseInt(subset1white[a]) + 2);
  String x = Integer.toString(Integer.parseInt(subset1white[a]) - 2);
  String y = Integer.toString(Integer.parseInt(subset1white[a]) + 10);
  String z = Integer.toString(Integer.parseInt(subset1white[a]) - 10);

  String[] arithmetic = {w, x, y, z};

  for (int b=0; b<= arithmetic.length-1; b++) {
    if (arithmetic[b] == subset1black[a]) {
      result.add(new Integer(subset1black[a]));
    }
  }    
}