Jake
Jake

Reputation: 2907

Traversing through a generic collection

Lets say I have function

void sell(Collection<? extends T> items) {
   for (? e : items) {
      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".

Upvotes: 0

Views: 126

Answers (1)

John Kugelman
John Kugelman

Reputation: 361595

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);
}

Upvotes: 10

Related Questions