Renuz
Renuz

Reputation: 1667

How do you search for an item in a LinkedLIst?

For adding an item I use

public void add(Object s) {
    list.add(s);
}

For deleting an item I use

public void remove(Object s) {
    list.remove(s);
}

Now for searching the LinkedList when I use the dot operator and search the built in API I do not see anything that would suggest a search function. Would it be contains?

Upvotes: 1

Views: 294

Answers (6)

Arjun K P
Arjun K P

Reputation: 2111

Following code sample would make u understand

    // Assuming that we java imported java.util.LinkedList........

    LinkedList ll =new LinkedList();
    ll.add("red");
    ll.add("blue");
    ll.get(0);  // gets the first element.........
    ll.getFirst(); // returns the first element..
    ll.getLast(); // returns the last element....
    int position = ll.indexOf("red");        

    boolean status;
    status= ll.contains("red"); // returns true if list contains red or returns false....

Upvotes: 0

David Harkness
David Harkness

Reputation: 36562

Since it seems you want to know where the item is placed in the list so you can access the actual instance found, you want to use indexOf to find it and get to return the found instance. There is no method that combines the two.

List list = ...
Object item = ...
int index = list.indexOf(item);
if (index > 0) {
    Object found = list.get(index);
    ...
}

Upvotes: 2

ZeroOne
ZeroOne

Reputation: 3171

Yes, for searching you would use the contains method. Note, however, that searching through a LinkedList takes an O(n) time, i.e. the time depends linearly on the size of the list, so if your list is big and you do lots of searches, you will want to use some other data structure. For example, you should probably initialize your list like this:

Collection something = new LinkedList();

Then, if you figure out that the performance of the search operations is hurting your program, you would just do this instead:

Collection something = new LinkedHashSet();

For a fancier search you should use a Map instead of a list or any other collection, but that's an entirely different data structure.

Upvotes: 1

Paul Bellora
Paul Bellora

Reputation: 55233

contains(Object) is indeed what you're looking for. You could also use Collections.binarysearch(List, T) if the list is sorted in ascending order.

Upvotes: 0

premnathcs
premnathcs

Reputation: 555

Yes contains method in LinkedList API will return true if it contains the search element.

Upvotes: 2

David Titarenco
David Titarenco

Reputation: 33406

Yes, it's contains. If you want something fancier, you'll have to write your own implementation of a LinkedList or come up with some utility functions.

Upvotes: 0

Related Questions