计算机语言笔记javajava中List对象indexOf方法失效
xucanxxjava中List对象indexOf方法失效
事情的起因是在解析excel文件时,想通过这个方法返回对象对应的行号,结果出现了行号不准确的情况
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.util.LinkedList; import java.util.List;
public class Test { static void func(List<String> list) { for (String s : list) { try { System.out.println("do index: "+list.indexOf(s)+ " hashCode: " + s.hashCode()); } catch (Exception e) { System.out.println(list.indexOf(s) + " 有异常"); } } }
public static void main(String[] args) { List<String> list = new LinkedList<String>(List.of("a", "b", "c")); func(list); } }
|
类似于这种操作,但是这个代码是不会产生不匹配的情况的
输出为
1 2 3
| do index: 0 hashCode: 97 do index: 1 hashCode: 98 do index: 2 hashCode: 99
|
但是如果我将链表的第一个元素复制一份到链表尾部
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import java.util.LinkedList; import java.util.List;
public class Test { static void func(List<String> list) { for (String s : list) { try { System.out.println("do index: "+list.indexOf(s)+ " hashCode: " + s.hashCode()); } catch (Exception e) { System.out.println(list.indexOf(s) + " 有异常"); } } }
public static void main(String[] args) { List<String> list = new LinkedList<String>(List.of("a", "b", "c")); list.add(list.get(0)); func(list); } }
|
输出就变成了
1 2 3 4
| do index: 0 hashCode: 97 do index: 1 hashCode: 98 do index: 2 hashCode: 99 do index: 0 hashCode: 97
|
解释
这个本质上是因为在add进list的时候传入的是与第一个元素的引用,可以理解为最后一个元素与第一个元素是同一个对象。在遍历查找的时候自然就返回了第一个元素的位置
主要是这个方法名字具有一定误导性,并且其也是通过遍历查找的方式去查找元素,这样一来时间复杂度也会增加。个人不推荐使用这个方法。