Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array declaration in java

Tags:

java

arrays

can anyone tell me the error in this java declaration String[][] t=new String[15][15]; this works fine and if i use String[][] t=new String[][]; because i need to declare the variable t as dynamic as i am not sure how much values i am going to store in t.

like image 226
raju Avatar asked Oct 29 '10 17:10

raju


People also ask

What is dynamic array declaration?

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.

Is there a dynamic array in Java?

Hence, there arise dynamic arrays in java in which entries can be added as the array increases its size as it is full. The size of the new array increases to double the size of the original array.

What is meant by dynamic array in Java?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.


2 Answers

Use ArrayList (or other array object who can handle any number of objects). A java array always has a fixed length since some memory will be reserved for the array.

ArrayList creates such array as well to store the objects. Of you add more abjects as the current reserved size of the array than ArrayList will create a new bigger array (+50% if i'm correct). There are some other implementations that act a bit different (for example they create a new array 100% of the original one when the array is full. If performance is really important for you than you can look into this.

ArrayList<ArrayList<String> t = new ArrayList<ArrayList<String>();

void fill() {
    ArrayList<String> t2 = new ArrayList<String>();
    t2.add("somestring");
    String s = "someotherstring";
    t2.add(s);
    t.add(t2);
}
like image 132
Mark Baijens Avatar answered Nov 11 '22 01:11

Mark Baijens


If you don't know how big it needs to be just declare it as

String[][] t;

and once you know how big it needs to be you can do (before trying to use the array)

t = new String[15][15];

If you're never sure how big the array need to be, you'll need to use something like a List of Lists.

List<List<String>> t = new ArrayList<List<String>>;

public void add(String str, int row, int col) {
    while (row >= t.size())
        t.add(new ArrayList<String>());

    List<String> row_list = t.get(row);
    while (col >= row_list.size())
        row_list.add("");

    row_list.set(col, str);
}
like image 21
Brad Mace Avatar answered Nov 11 '22 02:11

Brad Mace