Prev Next

Java / Generics

What are Generic Methods?

Generic method are methods that is type parameterized.

public class GenericMethodExample {

	public static void main(String[] s) {

		String[] StrArray = new String[] { "Find", "the", "word", "in", "this",
				"Array" };

		System.out.println(contains(StrArray, "word"));

		Integer[] intArray = new Integer[] { 4, 5, 32, 100, 303, 2002, 465 };

		System.out.println(contains(intArray, 2002));
	}

	public static <T> boolean contains(T[] list, T itemToFind) {

		for (T listItem : list) {
			if (itemToFind == null) {
				if (listItem == null)
					return true;
			} else if (itemToFind.equals(listItem)) {
				return true;
			}

		}
		return false;
	}
}

More Related questions...

Show more question and Answers...


Comments & Discussions