集合迭代器不返回每个值
我试图从 Collection
返回序列并将其应用到 TextView
。当我设置文本时,仅设置一个值,即序列的最后一个值。当我打印序列时,为了检查它是否正常工作,所有内容都打印正确。据我所知,我通过说当迭代器 hasNext()
时,获取 next()
来做到这一点,在本例中,是曲目的名称。我已经尝试了一些其他方法来正确设置集合,但是在研究了如何使用迭代器和集合之后,我总是回到这种方法。我缺少什么?
public static String getTopTracks(String mArtistName) {
String returnTopTracks = "";
Collection<Track> top = Artist.getTopTracks(mArtistName, key);
Iterator<Track> itr = top.iterator();
while (itr.hasNext()) {
returnTopTracks = itr.next().getName();
System.out.println(returnTopTracks);
}
return returnTopTracks;
}
I'm trying to return the sequence from a Collection
and apply it to a TextView
. When I set the text, only one value is set, the last of the sequence. When I print the sequence, to check it's working, everything prints correctly. As far as I can tell, I'm doing this right by saying while the iterator hasNext()
, get next()
and in this case, the name of the track. I've tried a few other ways to set the Collection properly, but after researching how to use an Iterator and Collection a little more, I always end up back with this method. What is it I'm missing?
public static String getTopTracks(String mArtistName) {
String returnTopTracks = "";
Collection<Track> top = Artist.getTopTracks(mArtistName, key);
Iterator<Track> itr = top.iterator();
while (itr.hasNext()) {
returnTopTracks = itr.next().getName();
System.out.println(returnTopTracks);
}
return returnTopTracks;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能希望将您的热门曲目作为集合返回
}
You probably want to return your top tracks as a Collection
}
您发布的关于迭代器或其用法的代码没有任何问题;它将调用集合中每个对象的 getName() 方法。然而,您只返回最后一个这一事实可能会成为一个问题。
从您的描述来看,您似乎希望返回每个
Track
的getName()
方法返回的所有字符串。您需要返回一个已将所有这些内容放入其中的List
,或者可能只是在循环中连接该String
。There is nothing wrong with the code you posted in regard to the
Iterator
or it's usage; it will call every object in the collection's getName() method. The fact that you're only returning the last one could, however, be a problem.From your description it appears you would like to return all the Strings retured by each
Track
'sgetName()
method. You would need to return aList
that you've placed all of them into, or perhaps just concatenate thatString
in the loop.