Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add items to a Java array?

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?

like image 761
kamikaze_pilot Avatar asked Feb 21 '11 02:02

kamikaze_pilot


People also ask

How do you create an array of objects dynamically in Java?

As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array. In Java, resizable arrays are implemented as the ArrayList class ( java. util. ArrayList ).

How do you add dynamics to an array?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.


2 Answers

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

List<Integer> x = new ArrayList<Integer>(); x.add(1); x.add(2); 
like image 116
corsiKa Avatar answered Sep 22 '22 18:09

corsiKa


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.

like image 36
Paŭlo Ebermann Avatar answered Sep 22 '22 18:09

Paŭlo Ebermann