开发者

Traversing through a generic collection

开发者 https://www.devze.com 2023-01-26 09:22 出处:网络
Lets say I have function void sell(Collection<? extends T> items) { for (? e : item开发者_JAVA百科s) {

Lets say I have function

void sell(Collection<? extends T> items) {
   for (? e : item开发者_JAVA百科s) {
      stock.add(e);
   }
}

as you can see i want to iterate through the items, but I cannot use the notation ? e, because it spits out the error "illegal start of expression".


Each of the items in the collection is a T or a sub-class of T, so you can use T. You don't know the exact types of the items but that doesn't matter; you do know their common base class.

for (T e: items) {
    stock.add(e);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消