Let me first apologize if this is ridiculously elementary. This is my first time programming.
The issue here is that I need to print out a LinkedList. Could someone guide me as to what I'm doing wrong? Here's what I have:
public class Queue {
private LinkedList list;
public Queue() {
list = new LinkedList();
}
}
public class BankQueue {
static Queue q = new Queue();
public static void main(String[] args) {
//Insert a menu with a list of possible choices
public static void printQueue(Queue q) {
for (String s : q) {
System.out.println(q);
}
}
I keep getting errors saying that say that I can only iterate over an array or an instance of java.lang.Iterable. Thanks for the help. It's sincerely appreciated.
4 Answers 4
You need to iterate over a list, not over your class instance that in fact doesn't implement Iterable
, like
public void printQueue(Queue q) {
for(String s : q.getList()) {
//do anything with your string
}
}
Of course, it implies that your LinkedList
is in fact LinkedList<String>
and that you have a getter for list
field declared in your class like public List<String> getList() { return list; }
.
-
I had to add the getter, but that fixed my issue. Thanks for the help!TheExecutive2011– TheExecutive201104/25/2013 18:41:35Commented Apr 25, 2013 at 18:41
Your class Queue
is not iterable.
Incidentally, its name collides with java.util.Queue
, which is iterable.
If you're actually trying to iterate over the list
member of Queue
, you'll need to provide a getter for that (it's private), or write yourself a Visitor.
-
I actually did not realize that there was already a use for "Queue". Perhaps I'll change the name of this thing...TheExecutive2011– TheExecutive201104/25/2013 18:42:20Commented Apr 25, 2013 at 18:42
You don't appear to be iterating over the list
member of q
. You would need to implement the Iterable
interface, or iterate over q.list
directly.
The really proper way to do it would be to implement Iterable
.
You need to use iterator to loop through the LinkedList like below:
iterator = q.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next()+" ");
}
-
The OP has defined his own
Queue
class, which doesn't implementIterable
, and therefore does not have aniterator()
method.GriffeyDog– GriffeyDog04/25/2013 18:19:30Commented Apr 25, 2013 at 18:19 -
Ah. That explains why I couldn't get that to work. Sorry for the confusion with the class name. I didn't realize that there was already a use for "Queue". Thanks anyway.TheExecutive2011– TheExecutive201104/25/2013 18:44:03Commented Apr 25, 2013 at 18:44