您好,欢迎访问一九零五行业门户网

在Java中使用索引在向量中搜索元素

向量实现list接口并用于创建动态数组。大小不固定并且可以根据需要增长的数组称为动态数组。向量在使用和功能方面与arraylist非常相似。
在本文中,我们将学习如何在 java 中创建向量并通过索引搜索特定元素。我们先讨论一下vector。
矢量尽管 vector 在很多方面与 arraylist 相似,但也存在一些差异。 vector 类是同步的,并且它包含几个遗留方法。
同步 - 每当我们对向量执行操作时,它都会限制其同时访问多个线程。如果我们尝试同时通过两个或多个线程访问向量,它将抛出一个名为“concurrentmodificationexception”的异常。与 arraylist 相比,这使得它的效率较低。
旧类 - 在 java 1.2 版本发布之前,当集合框架尚未引入时,有一些类描述了该框架类的功能,并用于代替这些类。例如,向量、字典和堆栈。在 jdk 5 中,java 创建者重新设计了向量并使它们与集合完全兼容。
我们使用以下语法来创建向量。
语法vector<typeofcollection> nameofcollection = new vector<>();
这里,在typeofcollection中指定将存储在集合中的元素的数据类型。在nameofcollection中给出适合您的集合的名称。
通过索引搜索向量中元素的程序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[]) { // 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。
以上就是在java中使用索引在向量中搜索元素的详细内容。
其它类似信息

推荐信息