contains()方法boolean contains(object o)
如果此列表包含指定的元素,则返回true。更正式地说,如果且仅当此列表包含至少一个元素e,使得(o==null ? e==null : o.equals(e)),则返回true。
参数c - 要测试其在此列表中是否存在的元素。
返回值如果此列表包含指定的元素,则返回true。
抛出classcastexception - 如果指定元素的类型与此列表不兼容(可选)。
nullpointerexception - 如果指定元素为null且此列表不允许null元素(可选)。
示例以下是使用contains()方法的示例:
package com.tutorialspoint;import java.util.arraylist;import java.util.list;public class collectionsdemo { public static void main(string[] args) { list list = new arraylist<>(); list.add(new student(1, "zara")); list.add(new student(2, "mahnaz")); list.add(new student(3, "ayan")); system.out.println("list: " + list); student student = new student(3, "ayan"); if(list.contains(student)) { system.out.println("ayan is present."); } }}class student { private int id; private string name; public student(int id, string name) { this.id = id; this.name = name; } public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } @override public boolean equals(object obj) { if(!(obj instanceof student)) { return false; } student student = (student)obj; return this.id == student.getid() && this.name.equals(student.getname()); } @override public string tostring() { return "[" + this.id + "," + this.name + "]"; }}
输出这将产生以下结果 -
note: com/tutorialspoint/collectionsdemo.java uses unchecked or unsafe operations.note: recompile with -xlint:unchecked for details.list: [[1,zara], [2,mahnaz], [3,ayan]]ayan is present.
以上就是如何在java中检查arraylist是否包含某个元素?的详细内容。
