简体   繁体   中英

Reuse static string array in Java / Inheritance like concept inside string array

private static String[][] s1 = {
        { "a", "a1" },
        { "b", "b1" },
        { "c", "c1" },
        { "d", "d1" },
}

private static String[][] s2 = {
        { "c", "c1" },
        { "d", "d1" },
        { "e", "e1" },
        { "f", "f1" },
}

Here c,c1 and d,d1 is repeated in those string arrays. How to take that outside and put it in a common string array say s3, and s1 and s2 reuses/inherits it so that it need not be declared in two different places?

static String[] common = { "c", "c1" };

private static String[][] s1 = {
    { "a", "a1" },
    { "b", "b1" },
    common,
    { "d", "d1" }
}

private static String[][] s2 = {
    common,
    { "d", "d1" },
    { "e", "e1" },
    { "f", "f1" }
}

Works fine.

You can use ArrayList rather than String Array, since its very difficult to remove/insert elements if you use String array.

ArrayList<String[]> s1=new ArrayList<String[]>();
ArrayList<String[]> s2=new ArrayList<String[]>();

And use add() method to add all the elements, and scan the lists to find out the overlapped elements by using contains() method. Find that element and save&&remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM