【ArrayList源码】contains源码及使用

1 contains源码

   /**
     * 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&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *如果当前列表包含指定元素,则返回true。当且仅当当前列表包含至少一个元素
     * @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;//#1
    }

第#1行源码表示,如果indexOf(o)>=0,则contains返回值为true,否则返回false。即当前列表包含指定元素,则返回true,否则返回false。关于indexOf的使用,可以参考【ArrayList源码】indexOf源码及使用

2 contains使用

public class Test {
    
	public static void main(String[] args){
		 ArrayList<String> list = new ArrayList<>();
		 list.add("wo");
		 list.add("ni");
		 list.add("ta");
		 
		 System.out.println(list.contains("wo"));
	}
}

结果:

true

3 总结

如果当前列表包含指定元素,则contains返回true。

发布了107 篇原创文章 · 获赞 142 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/u013293125/article/details/96644854
今日推荐