我刚刚开始学习Java语言中的ArrayList类。我用下面的代码测试了ArrayList类及其方法:
import java.util.ArrayList;
public class NewArrayList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> myList = new ArrayList<String>();
String s = new String();
myList.add(s);
String b = new String();
myList.add(b);
int theSize = myList.size();
System.out.println("ArrayList size: " + theSize);
boolean isTrue = myList.contains(s);
System.out.println(isTrue);
int whereIsIt = myList.indexOf(s);
System.out.println(whereIsIt);
int whereIsIt2 = myList.indexOf(b);
System.out.println(whereIsIt2);
}
}indexOf方法显示对象的索引。因此,由于我在myList ArrayList对象引用中添加了两个对象s和b,因此索引中应该有两个对象。whereIsit和whereIsit2的输出都是0。不应该是0 1吗??
发布于 2014-05-27 12:48:43
您将向列表添加两个具有相同值(空字符串)的String对象。
所以你的列表看起来像这样
["", ""]然后,您将调用与indexOf("")等效的方法,其中indexOf(..)使用Object#equals(Object)方法比较对象。列表中的第一个元素等于"",因此返回索引。
附注:
请记住,Java是通过值传递的。变量无关紧要。重要的是被传递的引用的值。
发布于 2014-05-27 13:08:05
在使用http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html之前,请阅读文档中的方法说明
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. 和
public int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.发布于 2014-05-27 13:08:46
在这里,您只创建了两个对象,并且没有值,因此它将被视为空字符串。因此,Indexof将返回给定对象的第一个匹配项。
如果你给s和b分配了不同的值,那么就会得到你所期望的结果。请尝试使用以下代码。
String s = "String1";
myList.add(s);
String b = "String2";
myList.add(b);
int whereIsIt = myList.indexOf(s);
System.out.println(whereIsIt);
int whereIsIt2 = myList.indexOf(b);
System.out.println(whereIsIt2);https://stackoverflow.com/questions/23881232
复制相似问题