有人能告诉我这个Java声明中的错误吗:String[][] t=new String[15][15];
这行代码是可以正常工作的。如果我使用 String[][] t=new String[][];
,因为我不确定我需要在t中存储多少值,所以我需要将变量t声明为动态的。
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);
}
String[][] t;
一旦您知道它需要有多大,您就可以在尝试使用数组之前进行操作。
t = new String[15][15];
如果您不确定数组需要多大,您需要使用类似于列表的列表(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);
}
String[][] t = null;
,在使用t[0][0] = "ana"
时会出现异常错误,错误信息为“Exception in thread "main" java.lang.NullPointerException”。 - rajut[0][0] =
赋值之前,你仍然需要执行t = new String[sizeX][sizeY];
。 - Stephen PString[][] t;
可以先创建一个不指向任何对象的指针,然后一旦知道大小,再分配一个对象:
int n1,n2;
// calculate n1,n2
t = new String[n1][n2];
如果您需要一个大小可以改变的结构,最好使用ArrayList,它可以动态调整大小。
将其声明为 String [][]t = null;
并在获得实际长度后使用重新初始化它。
t=new String[x][y];
已经有几个很好的答案了,但是在Mark Baijens的答案的评论中透露出了这个问题的目的是raju需要一个键到多值的映射。
Mark回复该评论时建议使用HashMap<String, String> hashMap = new HashMap<String, String>();
,但这仅适用于单个键值对。
raju需要的是一个
Map<String, Collection<String>> t
= new HashMap<String, List<String>>();
为一个键添加第一个值需要对该桶初始化一个List,而添加其他值则需要获取现有的列表并添加新值。
请注意,我在声明中使用了Collection<String>
,因此如果值的顺序很重要,则可以是List,或者如果要防止在同一个键下出现重复值,则可以是Set。
这可能最好作为一个类本身来实现,也许
public class MultiValueMap<K, V> extends Map<K, V>
{
...
}
因此,在第一个put(key, value)
上初始化列表和随后的.add(value)
到列表中的操作可以在实现中隐藏。
s = t[3][12];
变成了s = t.get(3).get(12);
。 - Stephen PHashMap<String, String> hashMap = new HashMap<String, String>();
。 - Mark Baijens