Difference between Java ArrayList indexOf() method and String indexOf() method

1, ArrayList indexOf () method

The indexOf(Object obj) method returns the index value of the element in the dynamic array.

The returned value is:

Returns the index value of the obj element that first appears in the array, and the index subscript starts from 0

If the specified element does not exist in the dynamic array, the indexOf() method returns -1

ArrayList<String> aa = new ArrayList<>();
aa.add("上海");
aa.add("北京");
aa.add("a");
aa.add("p");
aa.add("p");
System.out.println(aa); // [上海, 北京, a, p, p]
int b = aa.indexOf("app");
int e = aa.indexOf("海");
int f = aa.indexOf("北京");
int h = aa.indexOf("p");
System.out.println(b);//结果为 -1 因为不存在 app 的值
System.out.println(e);//结果为 -1 因为不存在 海 的值
System.out.println(f);//结果为 1  北京出现的位置索引下标为1
System.out.println(h);//结果为 3  p第一次出现的位置索引下标为3

 2, String indexOf(String str) method

The indexOf(String str) method returns the first occurrence of a specified string value in the string, and the index subscript starts from 0

Returns -1 if no matching string is found.

String a = "A,B2,CDF,D,F";
int c = a.indexOf("B");
int g = a.indexOf("D");
int j = a.indexOf("F");
int k = a.indexOf("上");
int u = a.indexOf("D",7);
System.out.println(c);//结果为:2  B出现的位置索引下标为2
System.out.println(g);//结果为:6  D出现的位置索引下标为6
System.out.println(j);//结果为:7  F出现的位置索引下标为7
System.out.println(k);//结果为:-1 上 未出现返回-1
System.out.println(u);//结果为:9  在第7个位置开始查找字符 "D" 第一次出现的位置,所以是9

3、string.indexOf(String str,int  fromIndex)方法

str: the string value to be retrieved

fromIndex: specifies the position in the string to start searching

String a = "A,B2,CDF,D,F";
int u = a.indexOf("D",7);
System.out.println(u);//结果为:9  在第7个位置开始查找字符 "D" 第一次出现的位置,所以是9

 4. The difference between the two

ArrayList: The indexOf(Object obj) method returns the first occurrence of the index value of the element in the dynamic array

String: The indexOf(String str) method returns the position of the first occurrence of a specified string value in the string

5. The most misleading place is

For example, the above example:

There is a , (comma) in the String string , which is also counted as an index subscript

And ArrayList: return [Shanghai, Beijing, a, p, p] Among them (comma) is not counted as a subscript, it is to check the subscript according to the value of the array,

The query int b = aa.indexOf("app") is not [a,p,p] in the array

If there is [Shanghai, Beijing, a, p, p, app] in the array, return 5

6. Extension: ArrayList lastIndexOf() method and String lastIndexOf() method

ArrayList: The lastIndexOf(Object obj) method returns the last position of the index value of the element in the dynamic array

String: The lastIndexOf(String str) method returns the position of the last occurrence of a specified string value in the string

 

Guess you like

Origin blog.csdn.net/SUMMERENT/article/details/129324143