Java Collection How to - Extend the size of an array








Question

We would like to know how to extend the size of an array.

Answer

public class Main {
  public static void main(String[] args) {
    String[] names = new String[] { "A", "B", "C" };
//from ww  w  .j a  v  a  2  s  . co  m
    String[] extended = new String[5];

    extended[3] = "D";
    extended[4] = "F";

    System.arraycopy(names, 0, extended, 0, names.length);

    for (String str : extended)
      System.out.println(str);
  }
}

The code above generates the following result.