Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare dynamic String array in Java

Tags:

java

arrays

I am using String Array declare as zoom z[]=new String[422];. But this array stores value from 0 to 32, so I got null pointer exception after looping value 32.

How to solve this problem in java?

How can I declare a dynamic array in java ?

like image 548
sivaraj Avatar asked Aug 30 '10 14:08

sivaraj


People also ask

How do you declare a dynamic array?

Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.

How do you dynamically allocate an array in Java?

First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.


1 Answers

You want to use a Set or List implementation (e.g. HashSet, TreeSet, etc, or ArrayList, LinkedList, etc..), since Java does not have dynamically sized arrays.

List<String> zoom = new ArrayList<>(); zoom.add("String 1"); zoom.add("String 2");  for (String z : zoom) {     System.err.println(z); } 

Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:

List<String> zoom = Arrays.asList("String 1", "String 2", "String n"); 
like image 149
Chadwick Avatar answered Oct 11 '22 21:10

Chadwick