Java: Appending To An Array - Programming.Guide

Java Arrays

  1. Java Arrays (with examples)
  2. Maximum length of array
  3. ArrayIndexOutOfBoundsException
  4. Arrays vs ArrayLists (and other Lists)
  5. Matrices and Multidimensional Arrays
  6. Appending to an array
  7. Copying an array
  8. Inserting an element in an array at a given index
  9. Testing array equality

Featured Stack Overflow Post

In Java, difference between default, public, protected, and private StackOverflow screenshot thumbnail

Top Java Articles

  1. Do interfaces inherit from Object?
  2. Executing code in comments?!
  3. Functional Interfaces
  4. Handling InterruptedException
  5. Why wait must be called in a synchronized block

See all 190 Java articles

Top Algorithm Articles

  1. Dynamic programming vs memoization vs tabulation
  2. Big O notation explained
  3. Sliding Window Algorithm with Example
  4. What makes a good loop invariant?
  5. Generating a random point within a circle (uniformly)
Java: Appending to an array

In Java arrays can't grow, so you need to create a new array, larger array, copy over the content, and insert the new element.

Example: Append 40 to the end of arr

int[] arr = { 10, 20, 30 }; arr = Arrays.copyOf(arr, arr.length + 1); arr[arr.length - 1] = 40; // arr == [ 10, 20, 30, 40 ]

Apache Commons Lang

If you have Commons Lang on your class path, you can use one of the ArrayUtils.add methods.

Example: Append 40 to the end of arr

int[] arr = { 10, 20, 30 }; arr = ArrayUtils.add(arr, 40);

Comments

Be the first to comment!

Tag » How To Append An Array Java