java集合光加_阳光沙滩-java集合:使用新建对象检查数组是否包含问题

这样的问题很简单的,就算我从来没有学过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里的呀。

这就是结了吗?

这么简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值