开发者

JAVA Linked List How to loop through with a for loop?

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开发者_JAVA百科 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 (???)


}


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
}


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()+" ");  
}


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
}


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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜