Skip to content
Advertisement

Tag: iterable

Wildcard not allowed for Iterable in Java

I have following code setup. But this is not allowed as wildcard is not allowed for Iterable. What actually Java tries to a achieve here by not allowing this? What modifications would get this working? Answer When a class instance is created, it invokes the initializer of the super type. But you can’t use wildcards for instance creation, hence your

How can I make my class iterable so I can use foreach syntax?

I have Book and BookList classes. BookList is something like this: In my main class I want to print titles of books with in a for each loop: Eclipse says: Can only iterate over an array or an instance of java.lang.Iterable How can I get this working? Answer You need to implement the Iterable interface, which means you need to

Java: Get first item from a collection

If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator away. Is there a less wasteful way to do it? Answer Iterables.get(yourC, indexYouWant) Because really, if you’re using Collections, you should be using Google Collections.

Advertisement