Top 22 Java Generics Interview Questions You Must Prepare 03.Dec.2022

No. Because Node is not a subtype of Node. 

110@Consider This Class:
class Node Implements Comparable {
Public Int Compareto(t Obj) { /* ... */ }
// ...
}
will The Following Code Compile? If Not, Why?

Yes.

Node node = new Node<>();
Comparable comp = node;

120@What Is A Parameterized Or Generic Type?

Note the declaration of class:Instead of T, We can use any valid identifier.

  • class MyListGeneric<T>

In MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. In declaration of the class, we specified a constraint "T super Number". We can use the class MyListRestricted with any class that is a super class of Number class.

public final class Algorithm
{
    public static <T> void swap(T[] a, int i, int j)
{
        T temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

 

public class Pair {
    public Pair(Object key, Object value) {
        this.key = key;
        this.value = value;
    }
    public Object getKey()   { return key; }
    public Object getValue() { return value; }
    public void setKey(Object key)     { this.key = key; }
    public void setValue(Object value) { this.value = value; }
    private Object key;
    private Object value;
}

If you know the fact that Array doesn’t support Generics and that’s why Joshua bloach suggested to prefer List over Array because List can provide compile time type-safety over Array.

This is an extension of previous Java generics interview question. Instead of asking to write Generic method Interviewer may ask to write a type safe class using generics. again key is instead of using raw types you need to used generic types and always use standard place holder used in JDK.

A generic type is a type with formal type parameters. A parameterized type is an instantiation of a generic type with actual type arguments.

A generic type is a reference type that has one or more type parameters. These type parameters are later replaced by type arguments when the generic type is instantiated (or declared ). 

Example (of a generic type): 
interface Collection<E>  {  
  public void add (E x);  
  public Iterator<E> iterator(); 
}

The interface Collection has one type parameter E .  The type parameter E is a place holder that will later be replaced by a type argument when the generic type is instantiated and used. The instantiation of a generic type with actual type arguments is called a parameterized type 

Example (of a parameterized type): 

Collection<String> coll = new LinkedList<String>();

The declaration Collection<String> denotes a parameterized type, which is an instantiation of the generic type Collection ,  where the place holder E has been replaced by the concrete type String .

Generics are used to create Generic Classes and Generic methods which can work with different Types(Classes).

This generic interview question in Java may look confusing to any one who is not very familiar with Generics as in fist glance it looks like String is object so List<String> can be used where List<Object> is required but this is not true. It will result in compilation error. It does make sense if you go one step further because List<Object> can store any any thing including String, Integer etc but List<String> can only store Strings.

1List<Object> objectList;

2 List<String> stringList;

3

4 objectList = stringList;  //compilation error incompatible types

No. You cannot create a static field of the type parameter T. 

100@Given The Following Classes:
class Shape { /* ... */ }
class Circle Extends Shape { /* ... */ }
class Rectangle Extends Shape { /* ... */ }
class Node { /* ... */ }
will The Following Code Compile? If Not, Why?
node Nc = New Node<>();
node Ns = Nc;

Type Parameters: The type parameters naming conventions are important to learn generics thoroughly.

The commonly type parameters are as follows:

  • T - Type
  • E - Element
  • K - Key
  • N - Number
  • V - Value

Advantage of Java Generics:

There are mainly 3 advantages of generics. They are as follows:

Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

List list = new ArrayList();  
list.add("hello");  
String s = (String) list.get(0);//typecasting  
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();  
list.add("hello");  
String s = list.get(0);  

Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

List<String> list = new ArrayList<String>();  
list.add("hello");  
list.add(32);//Compile Time Error  

import java.util.*;
public final class Algorithm {
    public static <T extends Object & Comparable<? super T>>
        T max(List<? extends T> list, int begin, int end) {
       T maxElem = list.get(begin);
        for (++begin; begin < end; ++begin)
            if (maxElem.compareTo(list.get(begin)) < 0)
                maxElem = list.get(begin);
        return maxElem;
    }
}

 One hint is that LinkedHashMap can be used implement fixed size LRU cache where one needs to remove eldest entry when Cache is full. LinkedHashMap provides a method called removeEldestEntry() which is called by put() and putAll() and can be used to instruct to remove eldest entry. you are free to come up with your own implementation as long as you have a written a working version along with Unit test.

In MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example class below: In declaration of the class, we specified a constraint "T extends Number". We can use the class MyListRestricted with any class extending (any sub class of) Number - Float, Integer, Double etc.

class MyListRestricted<T extends Number> {
    private List<T> values;
    void add(T value) {
        values.add(value);
    }
    void remove(T value) {
        values.remove(value);
    }
    T get(int index) {
        return values.get(index);
    }
}

MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();
restrictedListInteger.add(1);
restrictedListInteger.add(2);
String not valid substitute for constraint "T extends Number".
//MyListRestricted<String> restrictedStringList = 
//                new MyListRestricted<String>();//COMPILER ERROR

You should use generics because:

  • The Java compiler enforces tighter type checks on generic code at compile time.
  • Generics support programming types as parameters.
  • Generics enable you to implement generic algorithms

A generic type can be declared as part of method declaration as well. Then the generic type can be used anywhere in the method (return type, parameter type, local or block variable type).

Consider the method below:

    static <X extends Number> X doSomething(X number){
        X result = number;
        //do something with result
        return result;
    }
The method can now be called with any Class type extend Number.

Integer i = 5;
Integer k = doSomething(i);

public static int findFirstGreaterThan(Comparable[] at, Comparable elem) {
    // ...
    }