简体   繁体   中英

Fill specific row in a 2D array Java

i was wondering if we can in java fill a specified case in a 2D array for example

String[][] Dictionary = new String[25][2];
Dictionary[count][] = word.getName();
Dictionary[][count] = word.getHint();

i don't know if am being clear in my question but all what i am searching for is to fill part by part the 2D array not all the row or all the columns

not shure what you are trying, but if you want to fill in whole columns or rows you could do that the following way:

int size=100;
int dest=50; //value of the column/row you want to fill
String[][] Dictionary = new String[size][size];
//LOOP FOR FILLING COLUMN  :
for (int i=0; i< size;i++){
Dictionary[i][dest] = word.getName();
}
//LOOP FOR FILLING ROW :
for (int i=0; i< size;i++){
Dictionary[dest][i] = word.getName();
}

IF you just want to puncutal enter a specific value at a specific index in your array you must fill in your prevered indices in the "breaks":

i=1; //index row
j==1;//index column
Dictionary[i][j] = word.getName();

There is no such thing as a 2D array in Java. Java only has arrays of arrays. So your 2D array is in fact an array of rows. A row being itself an array of Strings. So if you want to replace the third "row" of your array, you would use

dictionary[2] = new String[] {"hello", "world"};

If you want to fill the existing cells of the third row, you would use

dictionary[2][0] = "hello";
dictionary[2][1] = "world";

If you want to fill the second "column" of your array, you would use

dictionary[0][1] = "hello";
dictionary[1][1] = "world";
dictionary[2][1] = "!";
...

I believe you're trying to do something like this.

String[][] dictionary = new String[25][2];
Dictionary[count][0] = word.getName();
Dictionary[count][1] = word.getHint();

Depending on what you're trying to do you might be better off doing this a little differently. For instance if you're storing a collection of names for which you want to lookup a hint then you might want to look at using a map.

Map<String, String> dictionary = new HashMap<String, String>();
dictionary.put(word.getName(), word.getHint());

String hint = dictionary.get("name");

There's a shortcut for filling all the values of a particular row.

-> Arrays.fill(Dictionary[i],"value");

If you want to fill the whole 2D array.

for(String[] array : Dictionary) Arrays.fill(array,"value");

By this logic, you can fill any dimension array instead of iterating and assigning each value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM