การวนลูป List ใน Java

ในการวนลูปเพื่อเรียกข้อมูลต่างๆ จาก List เราสามารถเรียกดูข้อมูลได้ด้วยวิธีการดังต่อไปนี้ครับ.
  1. Iterator loop
  2. For loop
  3. For loop (Adcance)
  4. While loop
ตัวอย่าง
package demo.loop;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class LoopListExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  List lists = Arrays.asList(new String[] { "Miss you 1", "Miss you 2", "Miss you 3" });
  
  // iterator loop
  System.out.println("Example 1.... iterator");
  Iterator iterator = lists.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
  
  // for loop
  System.out.println("Example 2.... for");
  for (int i = 0; i < lists.size(); i++) {
   System.out.println(lists.get(i));
  }
  
  // for loop advance
  System.out.println("Example 3.... for advance");
  for (String temp : lists) {
   System.out.println(temp);
  }
  
  // while loop
  System.out.println("Example 4.... while");
  int j = 0;
  while (j < lists.size()) {
   System.out.println(lists.get(j));
   j++;
  }
 }
}

ผลลัพธ์ที่ได้คือ
Example 1.... iterator
Miss you 1
Miss you 2
Miss you 3

Example 2.... for
Miss you 1
Miss you 2
Miss you 3

Example 3.... for advance
Miss you 1
Miss you 2
Miss you 3

Example 4.... while
Miss you 1
Miss you 2
Miss you 3

About Nop

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment