Dynamic array declaration in java

can someone 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, since I'm not sure how many values โ€‹โ€‹I'm going to store in t.

+5
source share
7 answers

Use an ArrayList (or another array object that can handle any number of objects). Java array always has a fixed length, as some memory will be reserved for the array.

ArrayList creates such an array to store objects. More abjects are added from you as the current reserved size of the array than ArrayList will create a new array (+ 50% if I'm right). There are several other implementations that act a little differently (for example, they create a new array 100% of the original when the array is full. If performance is really important to you, you can study 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);
}
+8
source

If you donโ€™t know how big, you just need to declare it as

String[][] t;

and as soon as you find out how necessary it is, you can do ( before trying to use an array)

t = new String[15][15];

If you never know how large the array is, you 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);
}
+4
source

Java . , . . :

String[][] t;

, :

int n1,n2;
// calculate n1,n2
t = new String[n1][n2];

, , ArrayList, .

+1

String [][]t = null;

Reinitialize .

t=new String[x][y];
+1

:

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

Add .

0

, , , , .

, . ( , ) .

, :

, , , , , bemace.

, , , . API- Java Collections:

tutorial api

0

, , , .

, raju HashMap<String, String> hashMap = new HashMap<String, String>(); โ€” -.

raju -

Map<String, Collection<String>> t
    = new HashMap<String, List<String>>();

, .

. Collection<String> , , , , .

This is probably best implemented as a class itself, perhaps

public class MultiValueMap<K, V> extends Map<K, V>
{
    ...
}

therefore, initialization of the list in the first put(key, value)and subsequent .add(value)list can be hidden in the implementation.

0
source

All Articles