Java中list.contains()的用法

2年前 (2022) 程序员胖胖胖虎阿
246 0 0

一、用法:

list集合中contains() 用于判断集合中 是否 包含指定的元素。list会将括号内的元素和list中存在的元素进行逐个比对,若有相等的,返回结果为true,若没有则返回结果为false。

二、举例说明:

用下方代码验证:

  public static void main(String[] args) {
        List newList = new ArrayList();//创建一个空数组
        newList.add("name");
        newList.add("age");
        newList.add("sex");
        newList.add("birth");//往数组中加一些元素
        boolean res = false;
        if(newList.contains("birthday")){
            res=true;
            log.info("包含,返回"+res);
        }else {
            log.info("不包含,返回"+res);
        }
    }

测试newList数组中是否包含元素“birthday”
Java中list.contains()的用法

测试newList数组中是否包含元素“birth”
Java中list.contains()的用法

三、拓展

String类中的contains()方法:当且仅当此字符串包含指定的 char 值序列,即判断指定内容中是否包含括号中的内容
举例说明:

public static void main(String[] args) {
	String str="CSDN程序媛";
    boolean res = false;
    if(str.contains("程序媛")){
    	res=true;
        log.info("包含程序媛,返回"+res);
    }else {
        log.info("不包含程序媛,返回"+res);
    }

测试String类型“CSDN程序媛”是否包含“程序媛”
Java中list.contains()的用法
如果String类型的字符串中包含字母时,需要注意区分大小写
测试String类型“CSDN程序媛”是否包含小写“csdn”
Java中list.contains()的用法
若有不足之处,还请大家批评指正❤

版权声明:程序员胖胖胖虎阿 发表于 2022年11月22日 下午9:24。
转载请注明:Java中list.contains()的用法 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...