Java 使用索引搜索向量中的元素
向量实现了List接口,用于创建动态数组。大小不固定且可以根据需要增长的数组被称为动态数组。向量在使用和功能方面与ArrayList非常相似。
在本文中,我们将学习如何在Java中创建向量并通过其索引搜索特定元素。让我们先讨论向量。
向量
虽然向量在许多方面与ArrayList相似,但也存在一些区别。向量类是同步的,并包含了一些传统的方法。
同步 - 当我们对向量执行操作时,它会限制对多个线程的同时访问。如果我们尝试在相同时间由两个或多个线程访问向量,则会抛出一个名为“ConcurrentModificationException”的异常。这使得它与ArrayList相比效率较低。
传统类 - 在Java版本1.2发布之前,即引入集合框架之前,有一些类描述了该框架类的特性,并在那些类的位置使用。例如,Vector,Dictionary和Stack。在JDK 5中,Java的创造者重新设计了向量,并使其与集合完全兼容。
我们使用以下语法来创建一个向量。
语法
Vector<TypeOfCollection> nameOfCollection = new Vector<>();
在这里,在 TypeOfCollection 中指定将存储在集合中的元素的数据类型。在 nameOfCollection 中给出适合您的集合的名称。
通过索引在向量中搜索元素的程序
indexOf()
要通过索引在向量中搜索元素,我们可以使用这个方法。使用’indexOf()’方法有两种方法-
- indexOf(nameOfObject) - 它以一个对象作为参数,并返回其索引的整数值。如果对象不属于指定的集合,它将返回-1。
-
indexOf(nameOfObject, index) - 它接受两个参数,一个是对象,另一个是索引。它将从指定的索引值开始搜索对象。
示例1
在下面的示例中,我们将定义一个名为’vectlist’的向量,并使用’add()’方法将一些对象存储在其中。然后,使用带有单个参数的indexOf()方法,我们将搜索元素。
import java.util.*;
public class VectClass {
public static void main(String args[]) {
// Creating a vector
Vector< String > vectList = new Vector<>();
// Adding elements in the vector
vectList.add("Tutorix");
vectList.add("Simply");
vectList.add("Easy");
vectList.add("Learning");
vectList.add("Tutorials");
vectList.add("Point");
// storing value of index in variable
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[]) {
// Creating a vector
Vector< String > vectList = new Vector<>();
// Adding elements in the vector
vectList.add("Tutorix");
vectList.add("Simply");
vectList.add("Easy");
vectList.add("Learning");
vectList.add("Tutorials");
vectList.add("Point");
// storing value of index in variable
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[]) {
// Creating a vector
Vector< String > vectList = new Vector<>();
// Adding elements in the 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");
// storing value of index in variable
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
结论
本文中,我们讨论了几个示例,展示了在搜索Vector中的特定元素时indexOf()方法的有用性。我们也学习了Java中的Vector。