java indexof
向量类indexOf()方法 (Vector Class indexOf() method)
Syntax:
句法:
public int indexOf(Object ob);
public int indexOf(Object ob, int indices);
indexOf() method is available in java.util package.
indexOf()方法在java.util包中可用。
indexOf(Object ob) method is used to return the index of the first occurrence of the given element.
indexOf(Object ob)方法用于返回给定元素首次出现的索引。
indexOf(Object ob, int indices) method is used to find the index of the first occurrence of the given object in this Vector and searching starts at the given indices.
indexOf(Object ob,int index)方法用于查找此Vector中给定对象首次出现的索引,并从给定索引开始搜索。
These methods may throw an exception at the time of returning an index.
这些方法在返回索引时可能会引发异常。
IndexOutOfBoundsException: This exception may throw when the given parameter is not in a range (indices<0).
IndexOutOfBoundsException :当给定参数不在范围内(索引<0)时,可能引发此异常。
These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
这些是非静态方法,可通过类对象访问,如果尝试使用类名访问这些方法,则会收到错误消息。
Parameter(s):
参数:
In the first case, indexOf(Object ob),
在第一种情况下, indexOf(Object ob) ,
Object ob – represents the object for which index to be returned.
对象ob –代表要为其返回索引的对象。
In the first case, indexOf(Object ob, int indices),
在第一种情况下, indexOf(Object ob,int index) ,
- Object ob – represents the index of searching starts.
- 对象ob –表示搜索开始的索引。
- int indices – represents the object for which index to be returned.
- int index –代表要为其返回索引的对象。
Return value:
返回值:
In both the cases, the return type of the method is int,
在这两种情况下,方法的返回类型均为int 。
In the first case, it gets the index of the first occurrence of the given object when it exists otherwise it returns -1.
在第一种情况下,它在给定对象存在时获取给定对象首次出现的索引,否则返回-1。
In the second case, it returns the index of the first occurrence of the given object when exists.
在第二种情况下,它返回给定对象首次出现时的索引。
Example:
例:
// Java program to demonstrate the example
// of indexOf() method of Vector
import java.util.*;
public class IndexOfVector {
public static void main(String[] args) {
// Instantiates a vector object
Vector < String > v = new Vector < String > (10);
// By using add() method is to add
// the elements in vector
v.add("C");
v.add("C++");
v.add("SFDC");
v.add("JAVA");
v.add("C++");
//Display Vector
System.out.println("v: " + v);
// By using indexOf(object) method is used
// to return the index of first occurrence of the
// given object
System.out.println("v.indexOf(C++): " + v.indexOf("C++"));
// By using indexOf(object, indices) method is used
// to return the index of first occurrence of the
// given object and searching starts from the
// given indices
System.out.println("v.indexOf(C++,2): " + v.indexOf("C++", 2));
}
}
Output
输出量
v: [C, C++, SFDC, JAVA, C++]
v.indexOf(C++): 1
v.indexOf(C++,2): 4
翻译自: https://www.includehelp.com/java/vector-indexof-method-with-example.aspx
java indexof