Top 22 Java Generics Interview Questions
Q1. Given The Following Classes:
magnificence Shape /* ... */
elegance Circle Extends Shape /* ... */
magnificence Rectangle Extends Shape /* ... */
class Node /* ... */
will Th
No. Because Node isn't always a subtype of Node.
A hundred and ten@Consider This Class:
magnificence Node Implements Comparable
Public Int Compareto(t Obj) /* ... */
// ...
Will The Following Code Compile? If Not, Why?
Q2. Consider This Class:
elegance 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?
Q3. How Do You Declare A Generic Class?
Note the announcement of class:Instead of T, We can use any valid identifier.
Class MyListGeneric<T>
Q4. How Can We Restrict Generics To A Super Class Of Particular Class?
In MyListGeneric, Type T is described as a part of elegance announcement. Any Java Type can be used a kind for this elegance. If we'd want to restriction the kinds allowed for a Generic Type, we are able to use a Generic Restrictions. In statement of the elegance, we detailed a constraint "T wonderful Number". We can use the magnificence MyListRestricted with any magnificence that may be a excellent magnificence of Number class.
Q5. Write A Generic Method To Exchange The Positions Of Two Different Elements In An Array.
Public very last magnificence Algorithm
public static <T> void swap(T[] a, int i, int j)
T temp = a[i];
a[i] = a[j];
a[j] = temp;
Q6. What Is The Following Class Converted To After Type Erasure?
Public Class Pair
Public Pair(okay Key, V Value)
This.Key = Key;
This.Value
public elegance Pair
public Pair(Object key, Object price)
this.Key = key;
this.Cost = cost;
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 = price;
personal Object key;
non-public Object price;
Q7. Can We Use Generics With Array?
If you already know the reality that Array doesn’t assist Generics and that’s why Joshua bloach counseled to prefer List over Array due to the fact List can provide collect time type-safety over Array.
Q8. How To Write Parametrized Class In Java Using Generics ?
This is an extension of preceding Java generics interview query. Instead of asking to jot down Generic technique Interviewer might also ask to write a type secure magnificence the use of generics. Again key is instead of using uncooked sorts you need to used accepted types and always use standard location holder used in JDK.
Q9. What Is A Parameterized Or Generic Type?
A popular type is a kind with formal kind parameters. A parameterized type is an instantiation of a typical type with real type arguments.
A conventional type is a reference kind that has one or more kind parameters. These kind parameters are later changed by kind arguments when the widespread type is instantiated (or declared ).
Example (of a time-honored kind):
interface Collection<E>
public void upload (E x);
public Iterator<E> iterator();
The interface Collection has one type parameter E . The kind parameter E is an area holder in an effort to later get replaced by way of a kind argument whilst the popular kind is instantiated and used. The instantiation of a common kind with actual kind arguments is called a parameterized type
Example (of a parameterized kind):
Collection<String> coll = new LinkedList<String>();
The announcement Collection<String> denotes a parameterized kind, that's an instantiation of the usual type Collection , in which the area holder E has been replaced via the concrete type String .
Q10. What Are Generics?
Generics are used to create Generic Classes and Generic methods that can paintings with exceptional Types(Classes).
Q11. 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;
No. The extra than (>) operator applies most effective to primitive numeric types.
Q12. Can You Pass List<string> To A Method Which Accepts List<object>?
This familiar interview question in Java can also appearance puzzling to any individual who isn't always very familiar with Generics as in fist glance it looks like String is item so List<String> can be used wherein List<Object> is required however this isn't always true. It will bring about compilation errors. It does make experience if you cross one step similarly due to the fact List<Object> can shop any any thing which includes String, Integer etc but List<String> can handiest keep Strings.
1List<Object> objectList;
2 List<String> stringList;
three
4 objectList = stringList; //compilation errors incompatible kinds
Q13. Will The Following Method Compile? If Not, Why?
Public Static Void Print(list List)
For (range N : List)
System.Out.Print(n + " ");
System.Out.
Yes.
Q14. Will The Following Class Compile? If Not, Why?
Public Class Singleton
Public Static T Getinstance()
If (instance == Null)
Instance = New Single
No. You can't create a static area of the sort parameter T.
One hundred@Given The Following Classes:
class Shape /* ... */
elegance Circle Extends Shape /* ... */
class Rectangle Extends Shape /* ... */
elegance Node /* ... */
will The Following Code Compile? If Not, Why?
Node Nc = New Node<>();
node Ns = Nc;
Q15. Whata Are The Type Parameters?
Type Parameters: The type parameters naming conventions are vital to learn generics thoroughly.
The normally kind parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Q16. What Are Advantages Of Using Generics?
Advantage of Java Generics:
There are in particular 3 blessings of generics. They are as follows:
Type-protection : We can preserve simplest a single type of objects in generics. It doesn’t allow to keep different gadgets.
Type casting isn't required: There is not any want to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.Add("hello");
String s = (String) list.Get(zero);//typecasting
After Generics, we do not need to typecast the item.
List<String> listing = new ArrayList<String>();
list.Upload("hiya");
String s = listing.Get(0);
Compile-Time Checking: It is checked at assemble time so problem will not occur at runtime. The excellent programming strategy says it's far some distance better to address the problem at assemble time than runtime.
List<String> listing = new ArrayList<String>();
list.Add("hi there");
list.Upload(32);//Compile Time Error
Q17. Write A Generic Method To Find The Maximal Element In The Range [start, End) Of A List.
Import java.Util.*;
public final class Algorithm
public static <T extends Object & Comparable<? Super T>>
T max(List<? Extends T> list, int start, int cease)
T maxElem = listing.Get(start);
for (++start; begin < cease; ++start)
if (maxElem.CompareTo(listing.Get(start)) < 0)
maxElem = list.Get(begin);
go back maxElem;
Q18. Write A Program To Implement Lru Cache Using Generics ?
One hint is that LinkedHashMap can be used put into effect fixed size LRU cache where one wishes to cast off eldest entry while Cache is complete. LinkedHashMap gives a technique known as removeEldestEntry() that is called through put() and putAll() and may be used to educate to put off eldest entry. You're unfastened to come up with your own implementation as long as you have a written a operating version together with Unit check.
Q19. How Can We Restrict Generics To A Subclass Of Particular Class?
In MyListGeneric, Type T is described as a part of class declaration. Any Java Type can be used a kind for this elegance. If we'd want to restriction the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example elegance underneath: In statement of the elegance, we targeted a constraint "T extends Number". We can use the class MyListRestricted with any class extending (any sub magnificence of) Number - Float, Integer, Double and many others.
Elegance MyListRestricted<T extends Number>
private List<T> values;
void add(T value)
values.Upload(cost);
void get rid of(T price)
values.Remove(price);
T get(int index)
go back values.Get(index);
MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();
restrictedListInteger.Add(1);
restrictedListInteger.Add(2);
String now not legitimate substitute for constraint "T extends Number".
//MyListRestricted<String> restrictedStringList =
// new MyListRestricted<String>();//COMPILER ERROR
Q20. If The Compiler Erases All Type Parameters At Compile Time, Why Should You Use Generics?
You have to use generics because:
The Java compiler enforces tighter kind assessments on ordinary code at bring together time.
Generics help programming types as parameters.
Generics allow you to put in force typical algorithms
Q21. Can You Give An Example Of A Generic Method?
A everyday type can be declared as part of approach announcement as properly. Then the typical type may be used everywhere inside the technique (return kind, parameter type, neighborhood or block variable type).
Consider the approach underneath:
static <X extends Number> X doSomething(X variety)
X end result = quantity;
//do some thing with end result
go back result;
The technique can now be known as with any Class kind extend Number.
Integer i = 5;
Integer ok = doSomething(i);
Q22. What Is The Following Method Converted To After Type Erasure?
Public Static >
Int Findfirstgreaterthan(t[] At, T Elem)
// ...
Public static int findFirstGreaterThan(Comparable[] at, Comparable elem)
// ...
