3

Hello I am trying to create a for loop that loops through the linked list. For each piece of data it will list it out individually. I am trying to learn linked list here, so no Array suggestions please. Anyone know how to do this?

Example Output:

  1. Flight 187
  2. Flight 501

CODE I HAVE SO FAR BELOW:

public static LinkedList<String> Flights = new LinkedList<String>();

public flightinfo(){
String[] flightNum = {"187", "501"};
        for (String x : flightNum)
        Flights.add(x);

                for (???)


}
1
  • Why are you iterating over the linked list? I'm confused by what you are trying to do. Right now, you have a LinkedList and an array of Strings, and you are iterating over that array of Strings to add them to a LinkedList. I don't understand what your end goal is. Commented Jun 5, 2011 at 20:52

7 Answers 7

16

Just use the enhanced for-loop, the same way you'd do it with an array:

for(String flight : flights) {
   // do what you like with it
}
Sign up to request clarification or add additional context in comments.

Comments

8

If I understand you correctly, you have to get a reference to the List's iterator and use that to cycle through the data:

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

Comments

2
for(String y : Flights) {
//...
}

The same way as arrays, since it inherits from Iterable<T>

As pointed out by @Cold Hawaiian this only works for Java >= 5.0

If pre 5.0 use:

ListIterator<String> iter = Flights.iterator();
while(iter.hasNext()) {
  String next = iter.next();
  // use next
}

1 Comment

This worked I copied the first for loop which was my mistake as it didn't teach me anything. Now I get it though!! Thanks
1

You should use a ListIterator (see Java API for more information).

Comments

0

If you have distinct values in the linked list , this would work :

for(Iterator<String> i = Flights.listIterator(); i.hasNext();){
    String temp = i.next();
    System.out.println(Flights.indexOf(temp)+1+". Flight "+temp );
}

If you do not have distinct values in the linked list, this would work :

int i=0;
for(Iterator<String> iter = Flights.listIterator(); iter.hasNext();i++){
    String temp = iter.next();
    System.out.println(i+1+". Flight "+temp );
}

Hope this helps.

Comments

0

With Java8 Collection classes that implement Iterable have a forEach() method. With forEach() and lambda expressions you can easily iterate over LinkedList

flights.forEach(flight -> System.out.println(flight));

Comments

-3
while(!flights.isEmptry) {
  System.out.println(flights.removeFirst());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.