Pages

April 06, 2016

#Java: Part 7-Core Java Interview Questions and Answers (Generics)

> > Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

What is Generics in Java ?
Generics is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, provides compile time type-safety and ensures that you only insert correct Type in collection and avoids ClassCastException in runtime.

Because of the Generics type casting is not required. e.g

Before Generics:
List list = new ArrayList();
list.add("Neuschwanstein Castle");
String s = (String) list.get(0);//typecasting 


After Generics:
List list = new ArrayList();
list.add("Neuschwanstein Castle");
String s = list.get(0);


Generics provides compile-time checking, e.g:
List list = new ArrayList();
list.add("Neuschwanstein Castle");
list.add(108);//Compile Time Error 


Generic Class: A class that can refer to any type is known as generic class. e.g:

class MyGenericClass{
    T obj;
    void add(T obj){this.obj=obj;}
    T get(){return obj;}


In the above example, T type indicates that it can refer to any type (like String, Integer, Student, LoadingOrder etc.). The type you specify for the class, will be used to store and retrieve the data.

class MyGenericClassTest{
public static void main(String args[]){
MyGenericClass m=new MyGenericClass();
m.add(7);
//m.add("Nathan");//Compile time error
System.out.println(m.get());
}} 


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

As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters

Generic Methods are those methods that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods:

  • All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).
  • Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
  • The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
  • A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).

// generic method printArray
public static < E > void printArray( E[] inputArray ) {
      for(E element : inputArray) {
         System.out.printf("%s ", element);
      }
}



What is bounded and unbounded wildcards in Generics Java?
The ? (question mark) symbol represents wildcard element. It means any type. If we write < ? extends Number > , it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.

Bounded and unbounded wildcards in Generics are two types of wildcard available on Java. Any Type can be bounded either upper or lower of the class hierarchy in Generics by using bounded wildcards. In short and represent bounded wildcards while represent an unbounded wildcard in generics.

Can we use Generics with Array?
Array doesn't support Generics.

Can you pass List < String >   to a method which accepts List < Object >

No, it will result in compilation error.

Difference between List and List< object > in Java?
List < ? > is List of unknown type while List < Object >  is essentially List of any Type. You can assign List < String > , List < Integer >  to List < ? >  but you can not assign List < String >  to List < Object > .


ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

1 comment: