Prev Next

Java / Generics

Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. 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;

2. Generics.

            Generics introduced in Java 1.5, facilitates strong-typing on the collection objects. Generics defines the object types that the collection can hold.

            It provides compile time type-safety and ensures that only the particular type is added in collection and eliminates ClassCastException in runtime.

3. Explain Generics using a sample code.

List list = new ArrayList();
list.add("No Generics is used ");
String s = (String) list.get(0);

In the above example, ArrayList can hold any type of objects, however we need to cast each object to its appropriate data type since get method's return type is Object. A string literal is added to the list and to get it from the list we need cast and store it.
If we store an employee object for example at the first index, then the 3rd line of code will throw a run-time Exception.

List<String> list = new ArrayList<String>();
list.add("Generics is implemented");
String s = list.get(0);   // no cast is required

In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.

4. What are Generic Types?

Generic types refers to generic class, abstract class or interface that is parameterized.

5. How can you suppress unchecked warning in Java ?

using @SuppressWarnings("unchecked") annotation.

List<String> myList = new ArrayList();

6. Example of a Bounded generic method.

static <T extends Number> T processTheNumber(T number){
        T result = number;
        return result;
7. How do you create a generic method which accepts generic types and return a generic type?

Replace all the raw type with the generic types like E,K, V etc and also add the list of generic types before the return type using <>.

public <K,V> V StoreThePair(K key, V value) {
                              return V;

8. Advantages of using Generics.

  • Helps creating type-safe collections objects.
  • Facilitate Strong type validation during the compile-time.
  • Eliminates Cast operator.
  • mproves the performance as Generics eliminates casting, boxing/unboxing.
  • Enables creation of generic algorithms, customizing the algorithm to be compatible with collection of different types, that are type-safe.

9. How do you define a generic type?

The Generic types are defined as <"GenericType"> e.g. to differentiate it from T if is a actual type.

10. Why Generics is required?

Generics helps finding issues during compile time rather than runtime. Generics are parameter for types.

11. What is type erasure?

Type erasure refers to the compile-time process where compiler erases type information during compile time and no type is available at runtime.

12. Example of a generic method from JAVA Collections API.

Collections.sort() that sorts collection of elements or objects of any type is a generic method.

13. What is Bounded wild-cards in Generics?

Bounded Wildcards impose bound on Type.

There are two types of Bounded wild-cards.

    • <? extends T>
    • <? super T>

Bounded wildcards are specified by List<? extends SuperClassType>

Bounded wildcards <? extends T> which impose an upper bound by ensuring that type must be sub class of T.

<? super T> imposes lower bound by ensuring Type must be super class of T.

14. Can we use Generics with Array?

Arrays does not support generics.

15. Can you pass List<Number> to a method which accepts List<Object>?

No. We encounter compilation error as it is incompatible.

16. Difference between List<Object> and List<?>.

You may add a new Objects or its sub-type into List whereas you could only insert null into the List<?>

17. Unbounded Wildcards.

Also known as Collection of Unknown type, specified using the wildcard character(?). for e.g., List , Collection.

An example of unbounded wildcards.

public static void printCollection(List<?> myList) {
    for (Object key: myList) {
        System.out.print(key + " ");

18. When do you implement Unbounded wildcards?

It is applicable when your method does not to have to do anything with the individual element types, for e.g. it can be used to determine the length of the list of any type.

19. What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warning for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

20. What is raw type in Java?

Raw type refers to generic type without specifying any parametrized type. For example, List is a raw type while List is a parameterized type. Raw types are retained for the backward compatibility to support code developed in older Java versions.


Comments & Discussions