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。所有三个结构的元素都打印在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP