[英]confusion related to arrays of arrays and iteration
我的主要方法中有一个局部变量ID,如下所示:
ID = new int[9];
ID[0] = 245;
ID[1] = 76644;
//etc
我也有一个arrayList对象,具有以下构造函数:
public Songs( String songName, String artistName, Integer duration, double price) {
this.songName = songName;
this.artistName =artistName;
this.duration = duration;
this.price = price;
我启动了一个二维数组,如下所示:
Songs reco[][];
reco = new Songs [99999] [];
for (int i=0; i<99999; i++) {
reco[i] = new Songs[20];
}
我想做的是将变量ID用作2d数组的第一个索引,如下所示:
reco[ID[7]][1] = new Songs("Human", "The Killers", 288, 0.19); // ID always is a 5 digit number
这样我就可以使用[ID [x]]作为参考来浏览2d数组,以便添加我可能遇到的持续时间的不同值。
假设以下2d数组:
reco[ID[7]][0] = new Songs("Better Now", "Post Malone", 239, 0.25);
reco[ID[7]][1] = new Songs("Human", "The Killers", 288, 0.19);
reco[ID[0]][2] = new Songs("Smells like teen spirit", "Nirvana", 214, 0.28);
预期结果应为:
"Customer:" [ID[7] total song duration is 239+288
"Customer:" [ID[0]] total song duration is 214
问题是,无论我设法制造什么循环,最终都会出现空指针错误,因为我正在将[ID [x]] [v]与[ID [x] [v + 1]比较,从而调用get()方法在每个上,最终达到空值。
希望我的问题很清楚。
最好的
(我知道,使用散列函数可以使数字迭代的重要性降低,尽管这不是我现在想解决的问题)
空指针异常是由于默认情况下访问填充了空元素的数组引起的。 您正在使用类似的元素
reco [ID [7]] [1] = ...
无需检查ID数组中的索引7是元素还是null。
如果要创建一个像新Songs[99999]
一样长的数组Songs[99999]
,则应使用列表和迭代器,这样就不会为“ 99999首乐曲”的长数组在内存中保留空间。
Songs reco[][]; reco = new Songs [99999] []; for (int i=0; i<99999; i++) { reco[i] = new Songs[20]; }
创建一个ArrayList或List并用如下歌曲列表填充它要容易得多:
List<List<Songs>> songs = new ArrayList<ArrayList<Songs>>();
然后,您可以像这样遍历整个列表:
for(List<Songs> tempSongsArray : songs)
{
for(Songs tempSong : tempSongsArray)
{
//Code using tempSong as Songs Element
}
}
使用列表应该是空指针安全的,因为列表中元素的长度<==>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.