How to search for an element in LinkedList(Custom Class)

package JavaLinkedListExample;

import java.util.LinkedList;

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

	public static void main(String args[]) {
		LinkedList<TestClass> linkedList = new LinkedList<TestClass>();
		/*
		 * Populating Linked list with sample data. Here we will populate the
		 * list with custom class which we have created.
		 */
		// Sample Data
		TestClass sampleData1 = new TestClass(1);
		TestClass sampleData2 = new TestClass(2);
		TestClass sampleData3 = new TestClass(3);
		TestClass sampleData4 = new TestClass(4);
		TestClass sampleData5 = new TestClass(5);

		TestClass sampleData6 = new TestClass(3);
		TestClass sampleData7 = new TestClass(13);

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

		/*
		 * contains(Object o) method returns true if this list contains the
		 * specified element(One or More times).
		 */
		boolean isExist = linkedList.contains(sampleData6);

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

		/*
		 * Result of the above code will be different then what is expected.
		 * There are two classes logically whose value are same(int i =3) Still
		 * JVM can not recognise it as same object. To make it work we need to
		 * override the equals() and hashcode() method.
		 */

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

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

	}
}

class TestClass {
	int i;

	TestClass(int i) {
		this.i = i;
	}

	@Override
	public String toString() {
		return "Object with value i as " + i;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 * equals method from Object
	 * class needs to be overridden in order to contain method work properly.
	 * This is the place where we can define the rule to check if two objects
	 * should be treated equal or not
	 */
	@Override
	public boolean equals(Object obj) {
		if (this.i == ((TestClass) obj).i)
			return true;
		else
			return false;
	}

}

 

Leave A Comment

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