这样的问题很简单的,就算我从来没有学过java,我也可以找到答案。
第一种方法,看注释:
/**
* Returns true if this list contains the specified element.
* More formally, returns true if and only if this list contains
* at least one element e such that
* (o==null ? e==null : o.equals(e)).
*
* @param o element whose presence in this list is to be tested
* @return true if this list contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (optional)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (optional)
*/
上面不是有说吗?
如果为null,则判空,如果非空就是o.equals(e)的比较。
第二个方法,如果没有注释呢?
假设别人的代码没有给出注释怎么办呢?
读源码呀,源码里没有秘密。
boolean contains(Object o);
这是list里的接口方法
我就写一个例子
List arrayList = new ArrayList<>();
arrayList.contains("test");
实现类是ArrayList吧,进去看ArrayList的源码
这就是它的比较代码
/**
* Returns true if this list contains the specified element.
* More formally, returns true if and only if this list contains
* at least one element e such that
* (o==null ? e==null : o.equals(e)).
*
* @param o element whose presence in this list is to be tested
* @return true if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
再看
indexOf(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.
* 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.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
再反问自己,调用equals方法的时候,调用的是谁的呀?你的对象都没有这个方法,又没有父类,那肯定是object里的呀。
这就是结了吗?
这么简单。