Java 集合 emptyIterator() 方法



描述

Java Collections emptyIterator() 方法用於獲取空迭代器。迭代器為空,其 hasNext 方法始終返回 false。next() 方法呼叫會丟擲 NoSuchElementException,remove() 方法會丟擲 IllegalStateException。

宣告

以下是 Java Collections emptyIterator() 方法的宣告。

public static <T> Iterator<T> emptyIterator()

引數

返回值

異常

獲取整數的空迭代器示例

以下示例演示瞭如何使用 Java Collection emptyIterator() 方法獲取整數的空迭代器。我們使用 emptyIterator() 方法建立了一個空迭代器,然後檢查迭代器是否包含元素。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Iterator;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty list    
      Iterator<Integer> emptyIterator = Collections.emptyIterator();

      System.out.println("Created empty iterator, it has elements: "+emptyIterator.hasNext());
   }    
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Created empty iterator, it has elements: false

獲取字串的空迭代器示例

以下示例演示瞭如何使用 Java Collection emptyIterator() 方法獲取字串的空迭代器。我們使用 emptyIterator() 方法建立了一個空迭代器,然後檢查迭代器是否包含元素。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Iterator;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty list    
      Iterator<String> emptyIterator = Collections.emptyIterator();

      System.out.println("Created empty iterator, it has elements: "+emptyIterator.hasNext());
   }    
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Created empty iterator, it has elements: false

獲取物件的空迭代器示例

以下示例演示瞭如何使用 Java Collection emptyIterator() 方法獲取 Student 物件的空迭代器。我們使用 emptyIterator() 方法建立了一個空迭代器,然後檢查迭代器是否包含元素。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Iterator;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty list    
      Iterator<Student> emptyIterator = Collections.emptyIterator();

      System.out.println("Created empty iterator, it has elements: "+emptyIterator.hasNext());
   }    
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Created empty iterator, it has elements: false
java_util_collections.htm
廣告