开发者

JAVA Linked List Search Linked List to compare data with user inputted data?

开发者 https://www.devze.com 2023-03-10 08:26 出处:网络
I have a linked list. Everything is go开发者_开发问答ing great inside of it. My only problem is how do I compare a variable to the contents to see if their is a match.

I have a linked list. Everything is go开发者_开发问答ing great inside of it. My only problem is how do I compare a variable to the contents to see if their is a match.

For instance I have a linked list full of names. I want the user to be able to enter a name in and search to see if that name exists in the Linked List.

User enters: Johnny

Program checks if Johnny is present in Linked List.

I don't have the code for this as I am not sure of what it would be.

public static LinkedList<String> NameList1 = new LinkedList<String>(); // How do I search its contents?

THANKS SO MUCH!!


Use the contains() method in the List interface.

if (NameList1.contains("Johnny")) {
    // code to execute if Johnny is in the list
}


Check out the Collections class. Within it is the goodness of the binarySearch method. Follow the instructions for that method (create a Comparator or implement various methods on your class, etc.) It'd be faster if you were using a random access list implementation, but it'll work.

0

精彩评论

暂无评论...
验证码 换一张
取 消