有没有一种方法可以在java中向数组定义中添加条件?

hpxqektj  于 2021-07-07  发布在  Java
关注(0)|答案(4)|浏览(306)

我想将数组添加到arraylist中,但有些值会根据条件进行更改。数组的大小总是相同的,但是结束值会不同。
您可以在下面的示例中看到,值[1,2,3]都是相同的,但是“111”或“222”都是基于bool编写的。到目前为止,我已经有了这个方法,但是我必须重复这些字段,当数组中的元素数量增加时,它会变得混乱,因为您必须复制所有内容,然后在else语句中更改需要更改的内容。

boolean bool = true;
    ArrayList<String[]> arrayList = new ArrayList<String[]>();

    if(bool){
        arrayList.add(
            new String[]{
            "1",
            "2",
            "3",
            "111",
            "111",
            "111",
            }
        );
    }
    else{
        arrayList.add(
            new String[]{
            "1",
            "2",
            "3",
            "222",
            "222",
            "222"
            }
        );
    }

    System.out.println(Arrays.deepToString(arrayList.toArray()));

有没有办法只声明[1,2,3]一次,然后根据条件写出“111”或“222”?比如说:

ArrayList<String[]> arrayList = new ArrayList<String[]>();
    arrayList.add(
            new String[]{
            "1",
            "2",
            "3",
            if(bool) add
            "111","111", "111",
            else add
             "222","222","222"
            }
        );
k3bvogb1

k3bvogb11#

你需要3个变量来决定
数组的第一部分是什么
从何处开始用条件元素填充数组
条件元素是什么

String[] firstPart = new String[]{"1", "2", "3"};
int index = 3;
String element = bool ? "111" : "222";

然后你复制第一部分然后填满剩下的部分。

System.arraycopy(firstPart, 0, a, 0, index);
Arrays.fill(a, index, a.length, element);
arrayList.add(a);

数组的初始化很简单

String[] a = new String[6];
xzlaal3s

xzlaal3s2#

您可以尝试以下操作:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

...

List<String[]> arrayList = new ArrayList<>();
boolean bool = false;
String[] res = 
        Stream.concat( Stream.of("1","2","3"), 
                       Collections.nCopies(3, bool ? "111" : "222").stream())
              .toArray(String[]::new);
System.out.println(Arrays.toString(res));

arrayList.add(res);
lmvvr0a8

lmvvr0a83#

我会这样做:

ArrayList<String[]> arrayList = new ArrayList<String[]>();

String[] toAdd = new String[]{"1","2","3","blah","blah"};

//now we replace blah and blah

if(bool){
   toAdd[3] = "111";
   toAdd[4] = "111";
}else{
   toAdd[3] = "222";
   toAdd[4] = "222";
}

//finally add this new array to the list
arrayList.add(toAdd);
u4dcyp6a

u4dcyp6a4#

使用局部变量作为可选字段值,这样可以使定义非常简短,例如:

String value = bool ? "111" : "222";
arrayList.add(new String[]{ "1", "2", "3", value, value, value});

相关问题