YouTube Icon

Interview Questions.

Top 100+ Java Generics Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Java Generics Interview Questions And Answers

Question 1. What Are Generics?

Answer :

Generics are used to create Generic Classes and Generic techniques that can paintings with unique Types(Classes).

Question 2. What Are Advantages Of Using Generics?

Answer :

Advantage of Java Generics:

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

Type-protection : We can preserve handiest a single type of items in generics. It doesn’t allow to shop other gadgets.

Type casting isn't required: There isn't any need to typecast the item.

Before Generics, we need to kind forged.

List list = new ArrayList();  
listing.Add("hiya");  
String s = (String) listing.Get(zero);//typecasting  
After Generics, we don't want to typecast the item.
List<String> listing = new ArrayList<String>();  
listing.Upload("howdy");  
String s = list.Get(0);  

Compile-Time Checking: It is checked at compile time so trouble will now not arise at runtime. The suitable programming approach says it is far higher to address the problem at bring together time than runtime.

List<String> list = new ArrayList<String>();  
list.Upload("hi there");  
listing.Upload(32);//Compile Time Error  

Adv Java Interview Questions
Question 3. If The Compiler Erases All Type Parameters At Compile Time, Why Should You Use Generics?

Answer :

You must use generics due to the fact:

The Java compiler enforces tighter type checks on prevalent code at collect time.
Generics guide programming types as parameters.
Generics allow you to put in force widespread algorithms
Question 4. Write A Generic Method To Exchange The Positions Of Two Different Elements In An Array.

Answer :

public final class Algorithm

    public static <T> void switch(T[] a, int i, int j)

        T temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    


 

Adv Java Tutorial
Question five. Will The Following Class Compile? If Not, Why?
Public Final Class Algorithm 
Public Static T Max(t X, T Y) 
Return X > Y ? X : Y;

Answer :

No. The extra than (>) operator applies only to primitive numeric kinds.

J2EE Interview Questions
Question 6. What Is The Following Class Converted To After Type Erasure?
Public Class Pair 

Public Pair(k Key, V Value) 
This.Key = Key;
This.Cost = Value;


Public K Getkey();  Return Key; 
Public V Getvalue();  Return Value; 

Public Void Setkey(k Key)  This.Key = Key; 
Public Void Setvalue(v Value)  This.Fee = Value; 

Private K Key;
Private V Value;


Answer :

public class Pair 
    public Pair(Object key, Object cost) 
        this.Key = key;
        this.Price = cost;
    
    public Object getKey()    go back key; 
    public Object getValue()  return cost; 
    public void setKey(Object key)      this.Key = key; 
    public void setValue(Object fee)  this.Fee = cost; 
    personal Object key;
    personal Object price;


Question 7. What Is The Following Method Converted To After Type Erasure?
Public Static >
Int Findfirstgreaterthan(t[] At, T Elem) 
// ...


Answer :

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

J2EE Tutorial Core Java Interview Questions
Question 8. Will The Following Method Compile? If Not, Why?
Public Static Void Print(listing List) 
For (number N : List)
System.Out.Print(n + " ");
System.Out.Println();


Answer :

Yes. 

Question nine. Write A Generic Method To Find The Maximal Element In The Range [start, End) Of A List.

Answer :

import java.Util.*;
public very last magnificence Algorithm 
    public static <T extends Object & Comparable<? Super T>>
        T max(List<? Extends T> list, int begin, int stop) 
       T maxElem = listing.Get(begin);
        for (++begin; begin < end; ++begin)
            if (maxElem.CompareTo(listing.Get(begin)) < 0)
                maxElem = list.Get(begin);
        go back maxElem;
    


JSP Interview Questions
Question 10. Will The Following Class Compile? If Not, Why?
Public Class Singleton 

Public Static T Getinstance() 
If (example == Null)
Instance = New Singleton();

Return Instance;

Private Static T Instance = Null;


Answer :

No. You can not create a static field of the kind parameter T. 

Core Java Tutorial
Question 11. Given The Following Classes:
elegance Shape  /* ... */ 
magnificence Circle Extends Shape  /* ... */ 
magnificence Rectangle Extends Shape  /* ... */ 
class Node  /* ... */ 
will The Following Code Compile? If Not, Why?
Node Nc = New Node<>();
node Ns = Nc;

Answer :

No. Because Node is not a subtype of Node. 

Java-Springs Interview Questions
Question 12. Consider This Class:
elegance Node Implements Comparable 
Public Int Compareto(t Obj)  /* ... */ 
// ...

Will The Following Code Compile? If Not, Why?

Answer :

Yes.

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

Adv Java Interview Questions
Question thirteen. What Is A Parameterized Or Generic Type?

Answer :

A regularly occurring type is a kind with formal type parameters. A parameterized kind is an instantiation of a universal kind with real type arguments.

A widespread kind is a reference type that has one or more kind parameters. These type parameters are later replaced via kind arguments whilst the established type is instantiated (or declared ). 

Example (of a regularly occurring type): 
interface Collection<E>    
  public void add (E x);  
  public Iterator<E> iterator(); 


The interface Collection has one kind parameter E .  The type parameter E is an area holder as a way to later get replaced through a kind argument when the widely wide-spread kind is instantiated and used. The instantiation of a normal kind with actual kind arguments is known as a parameterized kind 

Example (of a parameterized kind): 

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

The assertion Collection<String> denotes a parameterized type, which is an instantiation of the normal type Collection ,  where the vicinity holder E has been replaced via the concrete type String .

JSP Tutorial
Question 14. Can You Give An Example Of A Generic Method?

Answer :

A ordinary type may be declared as a part of technique announcement as well. Then the commonplace kind may be used everywhere within the technique (go back type, parameter type, nearby or block variable kind).

Consider the method under:

    static <X extends Number> X doSomething(X wide variety)
        X result = range;
        //do some thing with end result
        go back result;
    
The method can now be called with any Class type expand Number.

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

Question 15. How Can We Restrict Generics To A Super Class Of Particular Class?

Answer :

In MyListGeneric, Type T is defined as part of class declaration. Any Java Type may be used a kind for this class. If we would need to limit the kinds allowed for a Generic Type, we will use a Generic Restrictions. In statement of the elegance, we special a constraint "T superb Number". We can use the elegance MyListRestricted with any magnificence that may be a first rate elegance of Number elegance.

JMS(Java Message Service) Interview Questions
Question 16. How Can We Restrict Generics To A Subclass Of Particular Class?

Answer :

In MyListGeneric, Type T is defined as a part of elegance assertion. Any Java Type may be used a kind for this magnificence. If we'd want to restrict the kinds allowed for a Generic Type, we will use a Generic Restrictions. Consider the instance magnificence underneath: In announcement of the class, we unique a constraint "T extends Number". We can use the class MyListRestricted with any magnificence extending (any sub magnificence of) Number - Float, Integer, Double and so on.

Magnificence MyListRestricted<T extends Number> 
    private List<T> values;
    void upload(T cost) 
        values.Upload(price);
    
    void put off(T fee) 
        values.Do away with(fee);
    
    T get(int index) 
        go back values.Get(index);
    


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

Java-Springs Tutorial
Question 17. How Do You Declare A Generic Class?

Answer :

Note the assertion of sophistication:Instead of T, We can use any valid identifier.

Magnificence MyListGeneric<T>
Java applet Interview Questions
Question 18. Can We Use Generics With Array?

Answer :

If you know the truth that Array doesn’t help Generics and that’s why Joshua bloach cautioned to prefer List over Array because List can provide collect time type-safety over Array.

J2EE Interview Questions
Question 19. Can You Pass List<string> To A Method Which Accepts List<object>?

Answer :

This customary interview query in Java may additionally appearance confusing to any individual who is not very acquainted with Generics as in fist glance it seems like String is item so List<String> may be used in which List<Object> is needed but this is not true. It will bring about compilation mistakes. It does make feel if you pass one step similarly because List<Object> can store any any issue along with String, Integer and so on but List<String> can only store Strings.

1List<Object> objectList;

2 List<String> stringList;

3

4 objectList = stringList;  //compilation errors incompatible types

Java Tutorial
Question 20. How To Write Parametrized Class In Java Using Generics ?

Answer :

This is an extension of previous Java generics interview question. Instead of asking to put in writing Generic method Interviewer may additionally ask to jot down a kind safe elegance the use of generics. Again key's instead of the use of raw types you need to used universal kinds and always use popular vicinity holder used in JDK.

Java Interview Questions
Question 21. Write A Program To Implement Lru Cache Using Generics ?

Answer :

 One hint is that LinkedHashMap can be used put in force fixed length LRU cache where one desires to cast off eldest entry while Cache is complete. LinkedHashMap affords a technique referred to as removeEldestEntry() that is referred to as by way of placed() and putAll() and can be used to train to cast off eldest access. You're loose to come up with your own implementation as long as you have a written a operating version in conjunction with Unit check.

Question 22. Whata Are The Type Parameters?

Answer :

Type Parameters: The type parameters naming conventions are crucial to study generics very well.

The commonly type parameters are as follows:

T - Type
E - Element
K - Key
N - Number
V - Value
Java eight Tutorial




CFG