What are Generics?

A class, an interface or a method that act or operates on a parameterized type is called generics.
Here the term generics indicate to a parameterized types.

In other words, a class or an interface whose declaration has one or more type parameters is a generic class or interface.

Each and every  generic type defines a set of parameterized types, which contain  class or interface name followed by an angle bracketed list of actual type parameters corresponding to the generic type’s formal type parameters.

A simple example of defining generics are given below-
A snippet from the definitions of the interfaces List and Iterator in package java.util:

public interface List <E> {
    void add(E x);
    Iterator<E> iterator();
}

public interface Iterator<E> {
    E next();
    boolean hasNext();
}

 What is the General Form of a generic class?
The syntax for declaring a generic class:

class class-name<type-param-list>{ //…
and the syntax for declaring a reference to a generic class:

class-name<type-arg-list>var-name=
new class-name<type-arg-list>(cons-arg-list);

Why are generics used?
Generics are used because it add the stability to a code by making more of the bugs detectable at compile time.As generics enable ‘types’ to be parameters when defining classes,interfaces and methods.It provide a way to re-use the same code with the different inputs.
Code that uses generics has many benefits over non-generic code:
1.Stronger type checks at compile time.
2.Elimination of casts.
code snippet without generics requires casting:


List items = new ArrayList();

items.add("fruits");

String item = (String) items.get(0);

code snippet with generics does not requires casting:


List items = new ArrayList();

items.add("vegetables");

String item = items.get(0); // no cast

3.Enabling programmers to implement generic algorithms.

List the most commonly used Generics notations and naming convention,are they useful?
Yes,they are useful because naming convention helps us to understand the code easily.Generics type parameter names are single, uppercase letters to make it easily recognizable from java variables.Here,they are given below-
Generic term along with their meaning-
1.Set<E>
Generic Type , E is called formal parameter
2.Set<Integer>
Parametrized type , Integer is actual parameter here
3.<T extends Comparable>
Bounded type parameter
4.<T super Comparable>
Bounded type parameter
5.Set<?>
Unbounded wildcard
6.<? extends T>
Bounded wildcard type
7.<? Super T>
Bounded wildcards
8.Set
Raw type
9.<T super Comparable>
Recursive type bound
E – Element (used by the Java Collections Framework)
K – Key (Used in Map)
N – Number
T – Type
V – Value (Used in Map).

What are the formal parameters and type parameters?
The formal parameters are used in method declarations but the type parameters provide a way to re-use the same code with different inputs and the difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

What is a wildcard?
The question mark (?) is the wildcard in generics which represent an unknown type.It can be used as the type of a parameter, field,local variable and as a return type. It can never be used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

How many wildcard types are there?
To formulate subtle constraints of type variables. Wildcard types were invented for this purpose. There are three kinds of wildcard types:

1.Wildcard with upper bound
Syntax:- ? extends B
Meaning:- Any subtype of B.

2.Wildcard with lower bound
Syntax:- ? super B
Meaning:- Any supertype of B.

3.Unbounded wildcard
Syntax:- ?
Meaning:- Any type.

For example-
The following method in the LinkedList<E> class:


public void addAll(LinkedList<? extends E> upper)

{

ListIterator<E> iter = upper.listIterator();

while (iter.hasNext()) add(iter.next());

}

The method adds all elements of upper to the end of the linked list.

The addAll method doesn’t require a specific type for the element type of upper.Whether, it allows to use any type that is a subtype of E. For example,addAll is used to add a LinkedList<SalaryAccount> to a
LinkedList<BankAccount>.

Now a wildcard with a super bound, have another look at the min method.

A Comparable is a generic interface, the type parameter of the Comparable interface specifies the parameter type of the compareTo method.


public interface Comparable<T>;

{

int compareTo(T lower)

}

Therefore, we might want to specify a type bound:

public static <E extends Comparable <E>> E min(E[]a)

However, this bound is too restrictive. Suppose the BankAccount class
implements Comparable<BankAccount>. Then the subclass
SalaryAccount also implements Comparable<BankAccount> and not
Comparable<SalaryAccount>. If you want to use the min method with a
SalaryAccount array, then the type parameter of the Comparable interface
should be any supertype of the array element type:


public static <E extends Comparable<? super E>> E
min(E[] a).

Here is an example of an unbounded wildcard. The Collections class defines a method-


public static void reverse(List<?> list)

You can think of that declaration as a shorthand for


public static <T> void reverse(List<T> list).

What are wildcard guidelines in generics?
A wildcard guidelines in generics are as follows-
1.An “in” variable is defined with an upper bounded wildcard,
using the extends keyword.
2.An “out” variable is defined with a lower bounded wildcard,using the super keyword.
3.In the case where the “in” variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
4.In the case where the code needs to access the variable as both an “in” and an “out” variable, do not use a wildcard.
These guidelines do not apply to a method’s return type. Using a wildcard as a return type should be avoided.

 Is array support the generics?
No,you can use List over Array because List can provide compile time type-safety over Array.

What is the role of generic methods in raw types?
Static methods,non-static methods and constructors that are part of non-generic or raw type classes can be declared as generic.A raw type class is the non generic counterpart class to a generic class.For generic methods of non generic classes.The method’s return type must be preceded with the generic type parameteri.e..However there is no functional relationship between type parameter and the return type unless return type is of the generic type.


                     public class SpecialQueue {

                     public static <E> boolean add(E e) {...}

                     public static <E> E peek() {...}

                     }
                       

When calling the generic method,the generic type parameter is placed before the method name.Here, is used to specify the generic type parameter.


                  SpecialQueue.<String>add("Java Vapor");
                      

In what way an unchecked warning is suppressed in Java ?
Java compiler for Java 5 generates unchecked warnings when you mix  legacy code with generic code e.g.


List<String> rawList = new ArrayList()

     

Note: MyClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

This can happen when using an older API that operates on raw types and it can be suppressed by using @SuppressWarnings (“unchecked”) annotation.

 How constructors work with generics?
Constructors of generic classes do not require generic type parameters as arguments.


               //Generic Class

               public class Myclass <E> {

              //Constructor without arguments

               public class Myclass(){...}

               }

                 

An object of generic class could be instantiated as-


              Myclass<Sring> b = new

              Myclass<Sring>("Java Vapor");