我有一个 Vector 对象,其中包含不同内容的 String 元素,Vector 对象中的大小约为 10,000 个元素。因此,我不想像疯子一样循环,而是考虑使用 indexOf 来获取第一次出现。为了简单起见:
String curNode = "0";
Vector<String> stringVec = "1", "2", "3", "0", "1", "0", "1";
基于 vector API here ,如果我执行以下操作:
int firstOccur = stringVec.indexOf(curNode);
是否保证给我 firstOccur=3
?
另外,我不太确定 String 是否是不可变对象(immutable对象),或者是否有任何违反 equals
方法的行为在这里发挥作用。
最佳答案
Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
这是直接来自 api 的。 .indexOf
将保证返回 Vector
中对象的第一个实例,或 -1
如果在 Vector
中找不到该对象。据我所知,索引调用 .equals()
在对象上,而不是 ==
运算符(operator)。所以Strings
不应该有任何违规行为是不可变的。
关于java - Vector 类 java 的 indexOf 方法需要清晰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390535/