String a = "one";
String b = "two";
String c = "one";
String my[] = { a, b, c };
List<String> list = Arrays.asList(my);
System.out.println(list.indexOf("one"));
System.out.println(list.indexOf(c) + " " + list.indexOf(a) + " "+ list.indexOf(b));
运行结果为 0 0 1,求解?list里放的什么啊?不是三个元素么?
String b = "two";
String c = "one";
String my[] = { a, b, c };
List<String> list = Arrays.asList(my);
System.out.println(list.indexOf("one"));
System.out.println(list.indexOf(c) + " " + list.indexOf(a) + " "+ list.indexOf(b));
运行结果为 0 0 1,求解?list里放的什么啊?不是三个元素么?
//ArrayList的这个方法就是返回所在元素的下标啊,看看源码就知道了
public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
System.out.println(true);
}
//查找为null的元素,则直接比较地址
if (o == null) {
//为空时直接超找地址为null的元素,返回其索引
} else { //否则,进行equals比较,获取元素的索引
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
调用list的元素的话,用list.get(index)方法吧~~
通过 System.out.println(list); 得出:[one, two, one],是因为a, b, c都是变量,代入就是了,indexOf()返回索引值,无则-1。index就是索引的意思,尽量通过英语单词来记忆。