Java中的迭代器與集合


迭代器

它用於集合框架,以便根據需要檢索元素。

public interface Iterator

它可以與“next”函式一起使用來移動和訪問下一個元素。“remove”函式可以用來從資料結構中刪除元素。

與集合相比,它更快,因為與迭代器相關的操作較少。

下面是一個迭代器與列表一起工作的示例:

示例

 線上演示

mport java.io.*;
import java.util.*;
public class Demo{
   public static void main(String[] args){
      ArrayList<String> my_list = new ArrayList<String>();
      my_list.add("Its");
      my_list.add("a");
      my_list.add("sample");
      Iterator iterator = my_list.iterator();
      System.out.println("The list contains the following elements : ");
      while (iterator.hasNext())
      System.out.print(iterator.next() + ",");
      System.out.println();
   }
}

輸出

The list contains the following elements :
Its,a,sample,

名為 Demo 的類包含 main 函式。這裡,定義了一個新的陣列列表,並使用“add”函式向其中新增元素。定義一個迭代器,並將其迭代到陣列列表上,逐個迭代元素,然後列印到控制檯上。

集合

public interface Collection<E> extends Iterable<E>

這裡,E 指的是將要返回的元素的型別。集合框架用於定義不同的類和介面,這些類和介面將用於表示一組物件作為一個單一實體。

集合可以使用“add”函式、“iterate”函式、“remove”函式和“clear”函式分別新增元素、逐個迭代元素、刪除元素或清除整個結構。

讓我們來看一個例子:

示例

 線上演示

import java.io.*;
import java.util.*;
public class Demo{
   public static void main (String[] args){
      int my_arr[] = new int[] {56, 78, 90};
      Vector<Integer> my_vect = new Vector();
      Hashtable<Integer, String> my_hashtab = new Hashtable();
      my_vect.addElement(0);
      my_vect.addElement(100);
      my_hashtab.put(0,"sample");
      my_hashtab.put(100,"only");
      System.out.print("The first element in the array is ");
      System.out.println(my_arr[0]);
      System.out.print("The first element in the vector is ");
      System.out.println(my_vect.elementAt(0));
      System.out.print("The first element in the hashtable is ");
      System.out.println(my_hashtab.get(0));
   }
}

輸出

The first element in the array is 56
The first element in the vector is 0
The first element in the hashtable is sample

名為 Demo 的類包含 main 函式。這裡,定義了一個新的整數陣列,並向其中新增元素。現在定義了一個新的 Vector 和一個 Hashtable。使用“addElement”函式將元素新增到 Vector。使用“put”函式將元素新增到 Hashtable。所有三個結構的元素都列印在控制檯上。

更新於:2020年7月4日

323 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告