1

I need to append a dynamic string value to a new string array with known values.

static final String [] ARRAY = {"A","B","C"};
String d = "D"; // could be changing dynamically.

My question is to append a value to a new string array with a dynamic string value.

I need something like this.

String [] EXPECTED_ARRAY = {ARRAY, d}; // does not compile.

Expected Output: (local String array)

String [] EXPECTED_ARRAY = {"A", "B", "C", d};

Thanks in advance. BTW: Arrays, ArrayList can do this easily. Is there any other alternative ways.

Raaam
  • 95
  • 11
  • `ArrayList` is the way ... By the way, in JAVA, `Strings` are inmutable ... so any change to the value of D after been appended ... will not be reflected in the array content ! – Carlitos Way Aug 02 '16 at 05:27
  • I do not expect the value changes to be reflected once the new array is created. Thx. – Raaam Aug 02 '16 at 05:36
  • or if you want to go hard way , then you need to create a new array every time which is I guess you will like to stay away from – bananas Aug 02 '16 at 05:43

5 Answers5

2

Is there any other alternative ways?

If you want to add an element to the array (which has a fixed size), you could make arraycopy as ArrayList does it internally:

System.arraycopy(src, srcPos, dest, destPos, length);

Or allocate more space for dynamic elements, if you exactly know the length of resulted array:

String[] array = new String[EXPECTED_SIZE];

But it is not clever because the ArrayList class already exists exactly for these purposes.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • There are no other easy ways. No one would prefer arrayCopy unless otherwise there is a specific need. At-least to this context your answer is right. So marking as accepted answer. Thx. – Raaam Aug 03 '16 at 07:01
2

You can create you own method like following

String [] EXPECTED_ARRAY = append(ARRAY, d);


String[] append(String a[],String str){
    String[] b=new String[a.length+1];
    int i=0;
    for(;i<a.length;i++)
       b[i]=a[i];
    b[i]=str;
    return b;        
}
Loki
  • 801
  • 5
  • 13
0

Regex is not a good thing to use here. Use standard ways of doing this :

static final String [] ARRAY = {"A","B","C"};
public static void main(String[] args) throws Exception
{

    String d = "D"; // could be changing dynamically.
    List<String> l = new ArrayList<>(Arrays.asList(ARRAY));
    l.add(d); // can add multiple dynamic values.
    String[] arr = l.toArray(new String[l.size()]);
    System.out.println(Arrays.toString(arr));
}

Approach -2 :

String[] arr2 = new String[ARRAY.length + 1];
System.arraycopy(ARRAY, 0, arr2, 0, ARRAY.length);
arr2[arr2.length - 1 ] = d;
System.out.println(Arrays.toString(arr2));

O/P :

[A, B, C, D]
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

Simple way is to copy the values to a new array!

static final String[] ARRAY = {"A", "B", "C"};

public static void main(String[] args) {
    String[] EXPECTED_ARRAY = getExpectedArray("D", ARRAY);
    System.out.println(Arrays.toString(EXPECTED_ARRAY));
}

static String[] getExpectedArray(String addValue, String ... strings) {
    String [] returnArray = new String[strings.length + 1];
    returnArray[returnArray.length - 1] = addValue;
    System.arraycopy(strings, 0, returnArray, 0, strings.length);
    return returnArray;
}

Or minimal line code with BeanShell:

static final String[] ARRAY = {"A", "B", "C"};

public static void main(String[] args) throws Exception {
    String stringToAppend = "D";

    Interpreter interpreter = new Interpreter();
    String[] newArrayString = (String[]) interpreter.eval("new String [] {"
            + Arrays.toString(ARRAY).replaceAll("^\\[|\\]$", "\"")
                    .replaceAll(",", "\",\"")
            + ",\"" + stringToAppend + "\"" + "}");
}
James Jithin
  • 10,183
  • 5
  • 36
  • 51
0

you can try this way .

String strs[] = {"A","B","C"};
List<String> tempList = new ArrayList<>(Arrays.asList(strs));
tempList.add("D");
strs = tempList.toArray(new String[tempList.size()]);

if you want do a method for that .

private static String[] appendArray(String[] sts, String s)
{
    List<String> tempList = new ArrayList<>(Arrays.asList(sts));
    tempList.add(s);
    return (tempList.toArray(new String[tempList.size()]));
}

if you want multiples Strings on a single call.

private static String[] appendArray(String[] sts, String...s)
{
    List<String> tempList = new ArrayList<>(Arrays.asList(sts));
    if (s.length>0) tempList.addAll(Arrays.asList(s));
    return (tempList.toArray(new String[tempList.size()]));
}
Adliano Alves
  • 311
  • 2
  • 6