在这个例子中,我们将看到如何使用contains()
方法检查LinkedList
中是否存在特定元素:
public boolean contains(Object o)
:如果此列表包含指定的元素,则返回true
。更正式地,当且仅当此列表包含至少一个元素e
时才返回true
(o == null? e == null: o.equals(e)
)。
import java.util.LinkedList;
public class CheckLinkedList {
public static void main(String[] args) {
// Creating LinkedList of String Elements
LinkedList<String> linkedlist = new LinkedList<String>();
// Populating it with String values
linkedlist.add("AA");
linkedlist.add("BB");
linkedlist.add("CC");
linkedlist.add("DD");
linkedlist.add("EE");
// contains() method checks whether the element exists
if (linkedlist.contains("CC")) {
System.out.println("Element CC is present in List");
} else {
System.out.println("List doesn't have element CC");
}
//Checking for element FF
if (linkedlist.contains("FF")) {
System.out.println("Element FF is present in List");
} else {
System.out.println("List doesn't have element FF");
}
}
}
输出:
Element CC is present in List
List doesn't have element FF