在这种方法中,我试图返回当前存储在MediaItem类型的arraylist中的所有对象的String表示形式的常规数组,该数组称为itemList。(这在我的代码之前的注释中也有描述。)此方法是较大的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;
}
我必须创建一个新的arraylist来添加对象,因为原始arraylist的类型为。然后,我不得不将该arraylist(我命名为“ itemListAsString”)转换为常规数组,以便能够在方法结束时将其返回(我与教授确认,我们应该转换为常规数组)。
我尝试使用调试器,看起来代码在添加第一个对象,然后遍历并尝试再次添加该完全相同的对象。然后它将退出循环。由于我使用的是for循环,因此代码不应该移至arraylist中的下一个对象,而不是尝试添加相同的对象吗?
这是做同一件事的更现代的方式:
public String[] getItemListAsStringArray() {
return itemList.stream()
.filter(Objects::nonNull)
.map(Object::toString)
.toArray(String[]::new);
}
它们在功能上是等效的,但是这种方式具有功能编程的某些优点和缺点。基本上:用这种方式编写的代码通常不易出错,但要付出一定的代价。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句