在 Java 中使用索引搜索 Vector 中的元素
Vector 实现 List 接口并用于创建动态数组。大小不固定且可以根据需要增长的数组称为动态数组。Vector 在使用和功能方面与 ArrayList 非常相似。
在本文中,我们将学习如何在 Java 中创建 Vector 并通过其索引搜索特定元素。我们先讨论一下 Vector。
Vector
尽管 Vector 在许多方面与 ArrayList 相似,但也存在一些差异。Vector 类是同步的,并且包含几个遗留方法。
Synchronized - 每当我们对 Vector 执行操作时,它都会限制其同时对多个线程的访问。如果我们尝试同时通过两个或多个线程访问一个 Vector,那么它将抛出一个名为"ConcurrentModificationException"的异常。与 ArrayList 相比,这使其效率较低。
遗留类 - 在 Java 1.2 版发布之前,当未引入 Collection Framework 时,有一些类描述了此框架类的功能并用于代替这些类。例如,Vector、Dictionary 和 Stack。使用 JDK 5,Java 创建者重新设计了 Vector,并使它们与 Collections 完全兼容。
我们使用以下语法来创建 Vector。
语法
Vector<TypeOfCollection> nameOfCollection = new Vector<>();
在这里,在 TypeOfCollection 中指定将存储在集合中的元素的数据类型。在 nameOfCollection 中输入适合您的集合的元素。
通过索引搜索 Vector 中元素的程序
indexOf()
要通过索引搜索 Vector 中的元素,我们可以使用此方法。有两种使用"indexOf()"方法的方法 -
indexOf(nameOfObject) - 它以对象为参数并返回其索引的整数值。如果对象不属于指定的集合,则仅返回 -1。
indexOf(nameOfObject, index) - 它接受两个参数,一个是对象,另一个是索引。它将从指定的索引值开始搜索对象。
示例 1
在下面的示例中,我们将定义一个名为"vectlist"的向量,并使用"add()"方法在其中存储一些对象。然后,使用带有单个参数的 indexOf() 方法,我们将搜索元素。
import java.util.*;
public class VectClass {
public static void main(String args[]) {
// 创建一个向量
Vector< String > vectList = new Vector<>();
// 在向量中添加元素
vectList.add("Tutorix");
vectList.add("Simply");
vectList.add("Easy");
vectList.add("Learning");
vectList.add("Tutorials");
vectList.add("Point");
// 将索引值存储在变量中
int indexValue = vectList.indexOf("Tutorials");
System.out.println("Index of the specified element in list: " + indexValue);
}
}
输出
Index of the specified element in list: 4
示例 2
以下示例说明如果元素在集合中不可用,则"indexOf()"返回 -1。
import java.util.*;
public class VectClass {
public static void main(String args[]) {
// 创建一个向量
Vector< String > vectList = new Vector<>();
// 在向量中添加元素
vectList.add("Tutorix");
vectList.add("Simply");
vectList.add("Easy");
vectList.add("Learning");
vectList.add("Tutorials");
vectList.add("Point");
// 将索引值存储在变量中
int indexValue = vectList.indexOf("Tutorialspoint");
System.out.println("Index of the specified element in list: " + indexValue);
}
}
输出
Index of the specified element in list: -1
示例 3
以下示例说明了如何使用带有两个参数的"indexOf()"。编译器将从索引 3 开始搜索给定元素。
import java.util.*;
public class VectClass {
public static void main(String args[]) {
// 创建一个向量
Vector< String > vectList = new Vector<>();
// 在向量中添加元素
vectList.add("Tutorix");
vectList.add("Simply");
vectList.add("Easy");
vectList.add("Learning");
vectList.add("Tutorials");
vectList.add("Point");
vectList.add("Easy");
vectList.add("Learning");
// 将索引值存储在变量中
int indexValue = vectList.indexOf("Easy", 3);
System.out.println("Index of the specified element in list: " + indexValue);
}
}
输出
Index of the specified element in list: 6
结论
在本文中,我们讨论了一些示例,这些示例展示了 indexOf() 方法在 Vector 中搜索特定元素时的实用性。我们还了解了 Java 中的 Vector。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

