Java 集合 emptyListIterator() 方法



描述

Java 集合 emptyListIterator() 方法用於獲取空的列表迭代器。ListIterator 為空,其 hasNext 方法始終返回 false。next() 方法呼叫會丟擲 NoSuchElementException,而 remove() 方法會丟擲 IllegalStateException。

宣告

以下是 Java 集合 emptyListIterator() 方法的宣告。

public static <T> ListIterator<T> emptyListIterator()

引數

返回值

異常

獲取整數的空列表迭代器示例

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

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.ListIterator;

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

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

輸出

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

Created empty list iterator, it has elements: false

獲取字串的空列表迭代器示例

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

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.ListIterator;

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

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果。由於列表是不可變的,因此將丟擲異常。

Created empty list iterator, it has elements: false

獲取物件的空列表迭代器示例

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

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.ListIterator;

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

      System.out.println("Created empty list iterator, it has elements: "+emptyListIterator.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 list iterator, it has elements: false
java_util_collections.htm
廣告