/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
上面不是有说吗?
如果为null,则判空,如果非空就是o.equals(e)的比较。
第二个方法,如果没有注释呢?
假设别人的代码没有给出注释怎么办呢?
读源码呀,源码里没有秘密。
boolean contains(Object o);
这是list里的接口方法
我就写一个例子
List<String> arrayList = new ArrayList<>();
arrayList.contains("test");
实现类是ArrayList吧,进去看ArrayList的源码
这就是它的比较代码
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> 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 <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* 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;
}
这样的问题很简单的,就算我从来没有学过java,我也可以找到答案。
第一种方法,看注释:
上面不是有说吗?
如果为null,则判空,如果非空就是o.equals(e)的比较。
第二个方法,如果没有注释呢?
假设别人的代码没有给出注释怎么办呢?
读源码呀,源码里没有秘密。
这是list里的接口方法
我就写一个例子
实现类是ArrayList吧,进去看ArrayList的源码
这就是它的比较代码
再看
结果就出来了
再反问自己,调用equals方法的时候,调用的是谁的呀?你的对象都没有这个方法,又没有父类,那肯定是object里的呀。
这就是结了吗?
这么简单。
他的equals如果是这样,那么通过list.container()判断出来也是true
你上面的代码中,你的new Person(11,"Jack")是在建立一个新匿名的对象,而你的list.container()是在查询list里面是否有当前这个对象了,所以你新建立的对象肯定不在你的list里面啊,所以返回false。
你下面的代码中,你应该没展示完,你的p3这个对象,应该是在之前调用list.add(p3)把p3这个对象添加到了list里面了,所以后面调用list.container()的时候,就能查到他在你的list里面啦,所以返回true
最后,按照你上面的代码,只能返回false,因为你两次创建的都是匿名对象,使用一次之后,就找不到这个匿名对象了,就算你提前list.add(new Person(11,"Jack")),后面通过list.container(new Person(11,"Jack"))也是找不到的,因为第二次使用new Person(11,"Jack")又会是一个新的对象
这个是按照书本一模一样打的
课文原图