Java add to array

Previous
Next

In this post, we will see how to add elements to the array.


Using Apache’s common lang library

You can use varargs add method to add elements to array dynamically.

Here are the few add overloaded methods provided by ArrayUtils class

ArrayUtils's add methods

If you want to add more than one element, you can use ArrayUtils’s addAll methods.

ArrayUtils's addAll methods
Here is quick example using ArrayUtil’s add method

When you run above program, you will get below output.

1 2 3 4 5

By writing your own utility method

As Array is fixed in length, there is no direct method to add elements to the array, you can write your own utility method.
We have used varargs here to support n numbers of elements that can be added to array.

When you run above program, you will get below output:

1 2 3 4 5

As you can see, we are using object[] here. If you want to write a method specific to any data type, you can write that as well.
If you have frequent scenarios to add elements to array dynamically, I would recommend to use varargs instead of Array.

That’s all about Java add to array.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog