Java Generics Interview Questions for freshers experienced :-
1. What are Generics?
Generics are used to create Generic Classes and Generic methods which can work with different Types(Classes).
2. Why do we need Generics? Can you give an example of how Generics make a program more flexible?
Consider the class below:
class MyList {
private List<String> values;
void add(String value) {
values.add(value);
}
void remove(String value) {
values.remove(value);
}
}
MyList can be used to store a list of Strings only.
MyList myList = new MyList();
myList.add(“Value 1”);
myList.add(“Value 2”);
To store integers, we need to create a new class. This is problem that Generics solve. Instead of hard-coding String class as the only type the class can work with, we make the class type a parameter to the class.
Example with Generics
Let’s replace String with T and create a new class. Now the MyListGeneric class can be used to create a list of Integers or a list of Strings
class MyListGeneric<T> {
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);
}
}
MyListGeneric<String> myListString = new MyListGeneric<String>();
myListString.add(“Value 1”);
myListString.add(“Value 2”);
MyListGeneric<Integer> myListInteger = new MyListGeneric<Integer>();
myListInteger.add(1);
myListInteger.add(2);
3. How do you declare a Generic Class?
Note the declaration of class:Instead of T, We can use any valid identifier.
class MyListGeneric<T>
4. What are the restrictions in using generic type that is declared in a class declaration?
If a generic is declared as part of class declaration, it can be used any where a type can be used in a class – method (return type or argument), member variable etc. For Example: See how T is used as a parameter and return type in the class MyListGeneric.
5. How can we restrict Generics to a subclass of particular class?
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
6. How can we restrict Generics to a super class of particular class?
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.
7. Can you give an example of a Generic Method?
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);
8. How to write parametrized class in Java using Generics ?
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.
9. What are the type parameters?
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
10. Write a Generic method to find the maximal element in the range [begin, 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 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;
}
}
11. What is a generic function?
Generic functions are true functions that can be passed as arguments, returned as values, used as the first argument to funcall and apply, and otherwise used in all the ways an ordinary function may be used.
12. Why do we need generics in java?
Code that uses generics has many benefits over non-generic code:
- Stronger type checks at compile time: A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
- Elimination of casts: If you use generics, then explicit type casting is not required.
- Enabling programmers to implement generic algorithms: By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
13. How can you suppress unchecked warning in Java ?
using @SuppressWarnings(“unchecked”) annotation.
@SuppressWarnings(“unchecked”)
List<String> myList = new ArrayList()
14. 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.
15. 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.
16. 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.
17. How do you declare a Generic Class?
Note the declaration of class:Instead of T, We can use any valid identifier.
class MyListGeneric<T>
18. How can we restrict Generics to a super class of particular class?
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.
19. Can We Use Generics With Array?
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.
20. If The Compiler Erases All Type Parameters At Compile Time, Why Should You Use Generics?
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.