原文: https://beginnersbook.com/2014/07/java-check-if-a-particular-element-exists-in-linkedlist-example/

    在这个例子中,我们将看到如何使用contains()方法)检查LinkedList中是否存在特定元素:

    public boolean contains(Object o):如果此列表包含指定的元素,则返回true。更正式地,当且仅当此列表包含至少一个元素e时才返回trueo == null? e == null: o.equals(e))。

    1. import java.util.LinkedList;
    2. public class CheckLinkedList {
    3. public static void main(String[] args) {
    4. // Creating LinkedList of String Elements
    5. LinkedList<String> linkedlist = new LinkedList<String>();
    6. // Populating it with String values
    7. linkedlist.add("AA");
    8. linkedlist.add("BB");
    9. linkedlist.add("CC");
    10. linkedlist.add("DD");
    11. linkedlist.add("EE");
    12. // contains() method checks whether the element exists
    13. if (linkedlist.contains("CC")) {
    14. System.out.println("Element CC is present in List");
    15. } else {
    16. System.out.println("List doesn't have element CC");
    17. }
    18. //Checking for element FF
    19. if (linkedlist.contains("FF")) {
    20. System.out.println("Element FF is present in List");
    21. } else {
    22. System.out.println("List doesn't have element FF");
    23. }
    24. }
    25. }

    输出:

    1. Element CC is present in List
    2. List doesn't have element FF