How do I concatenate static string arrays [duplica

2020-04-16 02:54发布

Possible Duplicate:
How to concatenate two arrays in Java?

I have SET1 declared as a static String[] and I would like to declare SET2 as SET1 + few other parameters. Is it possible to declare SET2 statically similar (i.e. private static String[]) to SET1 but using the above definition, if not how to do this?

private static final String[] SET1 = { "1", "2", "3" };

SET2 = SET1 + { "4", "5", "6" };

标签: java
4条回答
Anthone
2楼-- · 2020-04-16 03:15
private static final String[] SET1 = { "1", "2", "3" };
private static final String[] SET2;

static
{
    List<String> set2 = new ArrayList<String>(Arrays.asList(SET1));
    set2.addAll(Arrays.asList("3", "4", "5"));
    SET2 = set2.toArray(new String[0]);
}
查看更多
放荡不羁爱自由
3楼-- · 2020-04-16 03:26

Maybe lists are easier in this case since arrays are fixed in length (by nature). You could do something like this if you want to instantiate it statically.

private static final List<String> SET1 = new ArrayList<String>();
private static final List<String> SET2 = new ArrayList<String>();
static {
    SET1.add("1");
    SET1.add("2");
    SET2.addAll(SET1);
    SET2.add("3");
}

Or use some kind of Collection utility library.

查看更多
姐就是有狂的资本
4楼-- · 2020-04-16 03:31

Look at Commons Util ArrayUtils.add:

static String[] SET2 = ArrayUtils.add(SET1, {"4", "5", "6" });
查看更多
▲ chillily
5楼-- · 2020-04-16 03:31

It's a big ugly:

private static final String[] SET1 = { "1", "2", "3" };
private static final String[] SET2 = concat(
    String.class, SET1, new String[]{"4", "5", "6"});

@SuppressWarnings("unchecked")
static <T> T[] concat(Class<T> clazz, T[] A, T[] B) {
    T[] C= (T[]) Array.newInstance(clazz, A.length+B.length);
    System.arraycopy(A, 0, C, 0, A.length);
    System.arraycopy(B, 0, C, A.length, B.length);
    return C;
 }
查看更多
登录 后发表回答