【发布时间】:2020-04-21 18:01:09
【问题描述】:
在此方法中,我试图返回当前存储在名为 itemList 的 MediaItem 类型的数组列表中的所有对象的字符串表示形式的常规数组。 (这在我的代码之前的 cmets 中也有描述。)这个方法是一个更大的 MediaList 项目的一部分,该项目包含几个子类,每个子类都是不同类型的媒体(歌曲、书籍、视频游戏等)。
我的问题是,当我运行代码并尝试打印 String 数组时,它只打印了第一个 String 对象,即 arraylist。我的循环只是将第一个 MediaItem 对象添加到 String 数组,而不是循环并添加每个连续的对象。这是为什么呢?
这是我的代码,以及教授给我们的说明:
/** TODO 11: implement this method.
* This method returns an array of the String representation of all of
* the MediaItem objects that are currently stored in the itemList.
* A String representation of a MediaItem is returned by calling its
toString() method.
* The array returned may not contain any NULL values. This method returns
an array of
* length 0 if the itemList is empty.
**/
public String[] getItemListAsStringArray(){
ArrayList<String> itemListAsString = new ArrayList<String>();
for (int i = 0; i < itemList.size(); i++) {
itemListAsString.add(itemList.get(i).toString());
String[] stringArray = itemListAsString.toArray(new String[0]);
if (stringArray.length == 0) {
return stringArray;
}
else {
itemListAsString.add(itemList.get(i).toString());
return stringArray;
}
}
String[] stringArray = itemListAsString.toArray(new String[0]);
return stringArray;
}
我必须创建一个新的数组列表来添加对象,因为原始数组列表的类型是 .然后,我必须将该数组列表(我将其命名为“itemListAsString”)转换为常规数组,以便能够在方法结束时将其返回(我与教授核实过,我们应该转换为常规数组)。
我尝试使用调试器,看起来代码正在添加第一个对象,然后循环并尝试再次添加完全相同的对象。然后它将退出循环。由于我使用的是 for 循环,代码不应该移动到 arraylist 中的下一个对象而不是尝试添加相同的对象吗?
【问题讨论】:
-
itemList是什么?它的长度是 0 吗? -
@jiveturkey 正如我所提到的,itemList 是一个 MediaItem 类型的数组列表。它没有指定的长度。
-
您在循环内部而不是在循环之后返回,因此只要将第一项添加到列表中,您就会返回数组。
-
@DavidConrad 哦,天哪,好的,谢谢。所以我应该摆脱循环内的那个 return 语句,并在最后保留它之外的那个?编辑:所以我想我根本不需要 if/else 语句?没有它们,代码似乎可以正常工作。
-
是的,你现在明白了。