How to search for an element in LinkedList

package JavaLinkedListExample;

import java.util.LinkedList;

/*
 * Here we will learn to check if given element exists in LinkedList or not.
 */
public class CheckIfElementExists {

	public static void main(String args[]) {
		LinkedList linkedList = new LinkedList();
		/*
		 * Populating Linked list with sample data.
		 */
		linkedList.add(1);
		linkedList.add(2);
		linkedList.add(3);
		linkedList.add(4);
		linkedList.add(5);
		linkedList.add(6);

		/*
		 * Showing the list of element this list has.
		 */
		System.out.println("Elements in List are");
		for (Object obj : linkedList)
			System.out.println(obj);

		/*
		 * Now we will search for an element in list with sample data. Answer
		 * shouuld be TRUE
		 */
		int valueExists = 4;
		/*
		 * boolean contains(Object o) method returns true if this list contains
		 * the specified element(One or More).
		 */
		boolean isExist = linkedList.contains(4);

		System.out.println("Element " + valueExists + " exists :" + isExist);

		/*
		 * Now we will search for an element in list which is not available.
		 * Answer should be FALSE
		 */
		int valueNotExists = 9;
		boolean isNotExist = linkedList.contains(valueNotExists);

		System.out.println("Element " + valueNotExists + " exists :"
				+ isNotExist);

	}
}

 

Leave A Comment

Your email address will not be published. Required fields are marked *