如何在Java中檢查列表是否包含某個專案?
可以使用indexOf()或contains()方法檢查列表中的元素。
語法 - indexOf() 方法
int indexOf(Object o)
返回此列表中指定元素的第一次出現的索引,如果此列表不包含該元素,則返回 -1。更正式地說,返回最小的索引 i,使得 (o==null ? get(i)==null : o.equals(get(i))),如果不存在這樣的索引,則返回 -1。
引數
o − 要搜尋的元素。
返回值
此列表中指定元素的第一次出現的索引,如果此列表不包含該元素,則返回 -1。
丟擲異常
ClassCastException − 如果指定元素的型別與該列表不相容(可選)。
NullPointerException − 如果指定元素為 null,並且此列表不允許 null 元素(可選)。
語法 - contains() 方法
boolean contains(Object o)
如果此列表包含指定的元素,則返回 true。更正式地說,當且僅當此列表至少包含一個元素 e 使得 (o==null ? e==null : o.equals(e)) 時,返回 true。
引數
o − 要在此列表中測試其存在性的元素。
返回值
如果此列表包含指定的元素,則返回 true。
丟擲異常
ClassCastException − 如果指定元素的型別與該列表不相容(可選)。
NullPointerException − 如果指定元素為 null,並且此列表不允許 null 元素(可選)。
示例
以下是使用各種方法從列表中查詢元素的示例:
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Student> 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");
System.out.println("Ayan is present: " + list.contains(student));
int index = list.indexOf(student);
System.out.println("Ayan is present at: " + index);
}
}
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 + "]";
}
}輸出
這將產生以下結果:
List: [[1,Zara], [2,Mahnaz], [3,Ayan]] Ayan is present: true Ayan is present at: 2
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP