开发者

How do I concatenate static string arrays [duplicate]

This question already has answers here: Closed 10 years ago.

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 + f开发者_运维问答ew 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" };


Look at Commons Util ArrayUtils.add:

static String[] SET2 = ArrayUtils.add(SET1, {"4", "5", "6" });


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.


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;
 }


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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜