TheExecutive2011
TheExecutive2011

Reputation: 25

Iterating through LinkedList in Java

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.

Upvotes: 2

Views: 5681

Answers (4)

Lavanya
Lavanya

Reputation: 319

You need to use iterator to loop through the LinkedList like below:

iterator = q.iterator(); 
  while (iterator.hasNext()) {
  System.out.print(iterator.next()+" ");  
}

Upvotes: 0

phoebus
phoebus

Reputation: 14921

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.

Upvotes: 0

CPerkins
CPerkins

Reputation: 9008

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.

Upvotes: 1

skuntsel
skuntsel

Reputation: 11742

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

Upvotes: 3

Related Questions