By kamikaze_pilot

2011-02-21 02:28:30 8 Comments

In PHP, you can dynamically add elements to arrays by the following:

$x = new Array();
$x[] = 1;
$x[] = 2;

After this, $x would be an array like this: {1,2}.

Is there a way to do something similar in Java?


@Paŭlo Ebermann 2011-02-21 15:13:38

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

A bit similar to the PHP behaviour is this:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;

Then you can write:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);


But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

@mist 2011-08-24 12:33:39

it's a lot smarter than the accepted solution. no wasted objects.

@Paŭlo Ebermann 2011-08-24 12:52:13

@Mihail: Actually, I normally don't recommend doing this, since for each add of an element a new array is created and the whole contents copied. (It depends on your use case, though - if you seldom add/remove anything, and often iterate/search, it might be okay.)

@mist 2011-08-25 12:58:46

ArrayUtils in the newer versions has method that does that. I'm pretty lazy to check the implementation, but I'm pretty sure they've written it well.

@corsiKa 2012-04-24 18:23:31

@MihailStoynov Actually, this is essentially what ArrayList does - except that instead of resizing on every add, when it runs out of room it doubles in size so it doesn't have to resize near as often.

@Tobias Sarnow 2013-08-30 08:03:43

@mist I've checked both implementations Arrays.copyOf and ArrayUtils.copyArrayGrow1 and the do exactly the same. But ArrayUtils is easier to use and I would recommend this library.

@ToolmakerSteve 2015-09-20 17:51:49

generics version of method could be public static <T> T[] add(T[] array, T element) { T[] result = Arrays.copyOf(array, array.length +1); result[array.length] = element; return result; } (I assume this is equivalent to what Apache ArrayUtils.add does.)

@Goddard 2018-06-15 14:58:41

You can add values to the end of an array in PHP. It is pretty easy. $array[] = 777;

@Paŭlo Ebermann 2018-06-15 15:28:25

@Goddard this fact is already stated in the question. The question asks how to duplicate this in Java (and it is not possible exactly, but this answer tries to approximate it as good as possible).

@Goddard 2018-06-15 15:29:10

No great answer, but in terms of PHP it isn't correect is all I am saying.

@Paŭlo Ebermann 2018-06-15 15:33:21

@Goddard I'm not sure what you feel is missing here. I think I'm quite clear in my first sentence that Java is not like PHP in respect to arrays (and just edited it to be even clearer), and the later paragraphs elaborate on it even more.

@Goddard 2018-06-15 15:34:30

Oh you changed it. Cool.

@Mav 2019-04-16 14:01:24

shouldn't it be result[org.length-1] = added;?

@Paŭlo Ebermann 2019-04-16 18:19:17

@Mav No, because org is one shorter than result.

@Jimmy 2017-01-30 14:16:21

I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.

First we should consider there is a difference between array and arraylist.

The question asks for adding an element to an array, and not ArrayList

The answer is quite simple. It can be done in 3 steps.

  1. Convert array to an arraylist
  2. Add element to the arrayList
  3. Convert back the new arrayList to the array

Here is the simple picture of it enter image description here

And finally here is the code:

Step 1:

public List<String> convertArrayToList(String[] array){
        List<String> stringList = new ArrayList<String>(Arrays.asList(array));
        return stringList;

Step 2:

public  List<String> addToList(String element,List<String> list){

            return list;

Step 3:

public String[] convertListToArray(List<String> list){
           String[] ins = (String[])list.toArray(new String[list.size()]);
           return ins;

Step 4

public String[] addNewItemToArray(String element,String [] array){
        List<String> list = convertArrayToList(array);
        list= addToList(element,list);
        return  convertListToArray(list);

@JoeG 2017-07-07 13:16:40

Upvoted because finally someone called out the difference between an actual array and ArrayList...

@Obaid 2017-07-25 05:29:52

Most complete and descriptive answer.

@Sashant Pardeshi 2017-09-30 09:48:01

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

package simplejava;

import java.util.Arrays;

 * @author sashant
public class SimpleJava {

     * @param args the command line arguments
    public static void main(String[] args) {
        // TODO code application logic here

            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            


        }catch(Exception exc){


@Nenad Bojović 2016-11-05 07:35:29

This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.

    int [] test = {12,22,33};
    int [] test2= new int[test.length+1];
    int m=5;int mz=0;
    for ( int test3: test)        
    test2[mz]=test3; mz++;        

    for ( int test3: test)


@mist 2011-08-25 12:59:43

Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

@marmor 2015-10-29 12:22:10

In the newer ArrayUtils it's: ArrayUtils.appendElement(String.class, origArray, "new element")

@user1948983 2013-01-04 15:18:20

keep a count of where you are in the primitive array

class recordStuff extends Thread
    double[] aListOfDoubles;
    int i = 0;

    void run()
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());

    void doStuff()
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
                if (a[j] == a[i]) count++;
            if (count > maxCount) 
                maxCount = count;
                maxValue = aListOfDoubles[i];
        return maxValue;

@Joe Day 2013-01-04 15:41:35

This doesn't really have anything to do with the original question of whether or not its possible to dynamically append new items to a Java primitive array.

@SSSM 2011-08-25 13:18:12

You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.

This Collection framework will be available in "java.util.*" package

For example if you use ArrayList,

Create an object to it and then add number of elements (any type like String, Integer ...etc)

ArrayList a = new ArrayList();
a.add(new Integer(3));

Now you were added 3 elements to an array.

if you want to remove any of added elements


again if you want to add any element


So the array size is incresing / decreasing dynamically..

@Ibrahim AshShohail 2011-02-21 03:07:26

Use an ArrayList or juggle to arrays to auto increment the array size.

@Ian Dallas 2011-02-21 02:34:00

You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.

See: Java List Tutorial

@Hovercraft Full Of Eels 2011-02-21 02:32:16

You probably want to use an ArrayList for this -- for a dynamically sized array like structure.

@corsiKa 2011-02-21 02:32:03

Look at java.util.LinkedList or java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();

@rharter 2012-12-01 01:36:09

This is a perfect answer except for one piece. Normally in Java we just use List's instead of primitive arrays, but for instances where you actually need a primitive array (like int[]) just use the toArray() method on List. Use the code above but use x.toArray() to get a primitive Array.

@corsiKa 2012-12-01 01:47:50

In 99% of cases (more like 99.99999% of cases) if you actually need a primitive array, you're doing something wrong, and it should be handled with OO principles. Unless you're interfacing with native code, or something like Oracle ARRAY objects or some silliness like that, you're much better off avoiding primitive arrays.

@thecoshman 2013-04-25 09:00:37

oh, all these comments about how you shouldn't use primitive arrays, if only it was that easy :(

@corsiKa 2013-04-25 17:08:58

@thecoshman I literally never need to use a primitive array except when working directly with database drivers or native code. Every other routine operation can utilize collections.

@trusktr 2013-10-02 09:05:34

WHy declare List<Integer> instead of ArrayList<Integer>?

@corsiKa 2013-10-02 14:38:09

@trusktr It's called "Programming to an interface" - here's an excellent post on it that you should read.

@trusktr 2013-10-03 05:15:17

I see. So maybe the programmer wants to reference multiple types of lists (like multiple pests in the example). That makes sense.

@corsiKa 2013-10-03 15:15:39

@trusktr That's one reason to do it. In this example, it's more along the lines of... using a List reference lets us kick ArrayList to the curb any time we want. If someone releases a better list, like SuperDuperAwesomeList, we might have a lot of work to do if we made our reference an ArrayList. ArrayList has things that List doesn't. If we rely on those things in our code, it becomes much more difficult to swap out.

@bestsss 2014-05-24 10:55:17

@corsiKa, write some compression/encoding algorithms without primitives and those cases are a lot more common than 99.(9). Маtrix impls scream primitivs as well. On a flip note if you interact with native code you use DirectBuffers not primitive arrays. In the end someone has to the metal, if you're stuck with databases and presentation, it's ok but the statement of 99% is just silly.

@corsiKa 2014-05-24 16:51:48

No they really aren't that common. Most Java developers are folks pumping out bloated webapps because it's cheaper to write tools in house than to buy them (or so management thinks). Most devs (honestly, 99% - that's 9,900,000 not using, and 100,000 using) could go an entire year and need to use an array maybe a dozen times. They might use an array, but they probably should use a list or other more advanced structure. Your example of Matrix impls is a great one: you only implement the Matrix logic once. You use matrices all the time, but you reference the Matrix class, not the arrays inside.

@bestsss 2014-05-24 18:49:55

@corsiKa, problem w/ matrices is that Matrix[] (or god forbid List<Matrix>) usually sucks for large datasets as the overhead is too huge to pay, so you end up with a sliding window over an array of primitives. Complex numbers are the poster child in that aspect - if you just have a class with 2 doubles/float inside, the object header really and indirections screws you big time. Personally I have written several encoders/decoders/compressors for market data where every bit is valuable, so larger objects (in the wire format) are out of question. Still 99% figure is a bit too high for my taste.

@ProgramFast 2016-07-06 00:24:36

The problem that you are all not seeing with Lists is that they can take up memory and are less efficient.

@corsiKa 2016-07-06 00:52:09

@ProgramFast We aren't seeing that problem because it isn't a problem. If you have to very often add a single element to an array, it's incredibly inefficient to use arrays instead of lists. As far as the amount of memory used, you can use different collections types to control the memory if it's a problem, but honestly, an arraylist is only ever twice as big as necessary. If your "array" is so big that being twice as big is a problem, well you really need to re-architect your design. The memory and efficiency of lists are very solid. There's a reason they're so widespread.

Related Questions

Sponsored Content

53 Answered Questions

38 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2659589 View
  • 2536 Score
  • 38 Answer
  • Tags:   php arrays unset

29 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1978123 View
  • 2291 Score
  • 29 Answer
  • Tags:   java arrays

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6816232 View
  • 8401 Score
  • 96 Answer
  • Tags:   javascript arrays

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

31 Answered Questions

[SOLVED] What's the simplest way to print a Java array?

  • 2009-01-03 20:39:39
  • Alex Spurling
  • 2310407 View
  • 1955 Score
  • 31 Answer
  • Tags:   java arrays printing

10 Answered Questions

[SOLVED] How can I add new array elements at the beginning of an array in Javascript?

  • 2011-11-10 00:35:22
  • Moon
  • 819665 View
  • 1602 Score
  • 10 Answer
  • Tags:   javascript arrays

18 Answered Questions

[SOLVED] How to insert an item into an array at a specific index (JavaScript)?

30 Answered Questions

[SOLVED] How to append something to an array?

30 Answered Questions

[SOLVED] How to avoid Java code in JSP files?

  • 2010-07-05 07:24:06
  • chmoelders
  • 286841 View
  • 1679 Score
  • 30 Answer
  • Tags:   java jsp scriptlet

Sponsored Content