[英]Iterator to return list
我試圖在增強的for循環的幫助下實現這一點,但我的問題是,如果我在下面的例子中使用迭代器,我如何確保我的返回類型正在拾取相應的“XYZ”值?
List<Apples> a1 = new List<Apples>();
if(a1.iterator().next().equals("XYZ")
{
return a1.iterator().next().getFruits();
}
可能你想實現以下內容
List<Apples> apples = new List<Apples>();
for(Apple a : apples) {
if("xyz".equals(a.getSomethingWhatReturnsString())) return a.getFruits();
}
為什么在這里使用迭代器? 一個簡單的get()
就可以了:
if (a1.get(0).equals("XYZ")) {
return a1.get(0).getFruits();
}
當然,如果你打算遍歷列表中的所有元素那么你就錯過了for
這里。 此外,你的代碼不起作用:它是蘋果列表,你無法將蘋果與字符串進行比較! 也許你的意思是這樣的,用你想要與"XYZ"
比較的適當屬性替換getStringAttribute()
:
for (Apple a : a1) {
if ("XYZ".equals(a.getStringAttribute())) {
return a.getFruits();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.