88

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
  • 73,284
  • 20
  • 146
  • 210
kamikaze_pilot
  • 14,304
  • 35
  • 111
  • 171
  • 4
    For all the answers below uses ArrayList but OP specifically ask for Array. i would like to know as well. – KJYe.Name Feb 21 '11 at 02:35
  • 4
    answer is 'No'. You have to specify the size of the array (or populate all elements) at the time of declaration/creation in Java. Please see http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html – Ritesh Feb 21 '11 at 02:38
  • I noticed that various Java function return arrays, so looked at the implementation of list(filter) in File.java. It uses a List internally and then converts it to an array at the end. List v = new ArrayList<>(); ... return v.toArray(new String[v.size()]); – xtempore Dec 29 '15 at 19:06

11 Answers11

115

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

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • 21
    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. – rharter Dec 01 '12 at 01:36
  • 1
    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. – corsiKa Dec 01 '12 at 01:47
  • 11
    oh, all these comments about how you shouldn't use primitive arrays, if only it was that easy :( – thecoshman Apr 25 '13 at 09:00
  • @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. – corsiKa Apr 25 '13 at 17:08
  • WHy declare List instead of ArrayList? – trusktr Oct 02 '13 at 09:05
  • @trusktr It's called "Programming to an interface" - [here's an excellent post on it that you should read.](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – corsiKa Oct 02 '13 at 14:38
  • I see. So maybe the programmer wants to reference multiple types of lists (like multiple pests in the example). That makes sense. – trusktr Oct 03 '13 at 05:15
  • 1
    @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. – corsiKa Oct 03 '13 at 15:15
  • 1
    @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. – bestsss May 24 '14 at 10:55
  • 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. – corsiKa May 24 '14 at 16:51
  • @corsiKa, problem w/ matrices is that Matrix[] (or god forbid List) 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. – bestsss May 24 '14 at 18:49
  • The problem that you are all not seeing with Lists is that they can take up memory and are less efficient. – WorkingRobot Jul 06 '16 at 00:24
  • @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. – corsiKa Jul 06 '16 at 00:52
67

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);

System.out.println(Arrays.toString(x));

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.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • it's a lot smarter than the accepted solution. no wasted objects. – mist Aug 24 '11 at 12:33
  • 2
    @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.) – Paŭlo Ebermann Aug 24 '11 at 12:52
  • 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. – mist Aug 25 '11 at 12:58
  • 1
    @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. – corsiKa Apr 24 '12 at 18:23
  • @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. – Tobias Sarnow Aug 30 '13 at 08:03
  • generics version of method could be `public static 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.) – ToolmakerSteve Sep 20 '15 at 17:51
  • You can add values to the end of an array in PHP. It is pretty easy. $array[] = 777; – Goddard Jun 15 '18 at 14:58
  • @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). – Paŭlo Ebermann Jun 15 '18 at 15:28
  • No great answer, but in terms of PHP it isn't correect is all I am saying. – Goddard Jun 15 '18 at 15:29
  • @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. – Paŭlo Ebermann Jun 15 '18 at 15:33
  • Oh you changed it. Cool. – Goddard Jun 15 '18 at 15:34
  • shouldn't it be `result[org.length-1] = added;`? – Mav Apr 16 '19 at 14:01
  • 1
    @Mav No, because `org` is one shorter than `result`. – Paŭlo Ebermann Apr 16 '19 at 18:19
20

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)
Renaud
  • 16,073
  • 6
  • 81
  • 79
mist
  • 1,853
  • 2
  • 19
  • 33
  • 2
    In the newer ArrayUtils it's: ArrayUtils.appendElement(String.class, origArray, "new element") – marmor Oct 29 '15 at 12:22
14

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){

            list.add(element);
            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);
}
Al.G.
  • 4,327
  • 6
  • 31
  • 56
Sal-laS
  • 11,016
  • 25
  • 99
  • 169
11

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

Ian Dallas
  • 12,451
  • 19
  • 58
  • 82
5

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

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
4

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("suman");
a.add(new Integer(3));
a.add("gurram");

Now you were added 3 elements to an array.

if you want to remove any of added elements

a.remove("suman");

again if you want to add any element

a.add("Gurram");

So the array size is incresing / decreasing dynamically..

SSSM
  • 39
  • 3
1

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

Ibrahim AshShohail
  • 2,072
  • 14
  • 19
0

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;
    }
}
  • 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. – Joe Day Jan 04 '13 at 15:41
0

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++;        
    } 
    test2[mz++]=m;
    test=test2;

    for ( int test3: test)

    {
      System.out.println(test3);
    }
0

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

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

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

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}
Sashant Pardeshi
  • 1,075
  • 7
  • 21