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:
[code lang=”java”]
public interface List <E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
[/code]
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:
[code lang=”java”]
List items = new ArrayList();
items.add("fruits");
String item = (String) items.get(0);
[/code]
code snippet with generics does not requires casting:
[code lang=”java”]
List items = new ArrayList();
items.add("vegetables");
String item = items.get(0); // no cast
[/code]
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:
[code lang=”java”]
public void addAll(LinkedList<? extends E> upper)
{
ListIterator<E> iter = upper.listIterator();
while (iter.hasNext()) add(iter.next());
}
[/code]
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.
[code lang=”java”]
public interface Comparable<T>;
{
int compareTo(T lower)
}
[/code]
Therefore, we might want to specify a type bound:
[code lang=”java”]
public static <E extends Comparable <E>> E min(E[]a)
[/code]
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:
[code lang=”java”]
public static <E extends Comparable<? super E>> E
min(E[] a).
[/code]
Here is an example of an unbounded wildcard. The Collections class defines a method-
[code lang=”java”]
public static void reverse(List<?> list)
[/code]
You can think of that declaration as a shorthand for
[code lang=”java”]
public static <T> void reverse(List<T> list).
[/code]
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.
[code lang=”java”]
public class SpecialQueue {
public static <E> boolean add(E e) {…}
public static <E> E peek() {…}
}
[/code]
When calling the generic method,the generic type parameter is placed before the method name.Here, is used to specify the generic type parameter.
[code lang=”java”]
SpecialQueue.<String>add("Java Vapor");
[/code]
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.
[code lang=”java”]
List<String> rawList = new ArrayList()
[/code]
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.
[code lang=”java”]
//Generic Class
public class Myclass <E> {
//Constructor without arguments
public class Myclass(){…}
}
[/code]
An object of generic class could be instantiated as-
[code lang=”java”]
Myclass<Sring> b = new
Myclass<Sring>("Java Vapor");
[/code]
I love this site…… i hope i will take lot of knowledge from here..
Already i have a concept about core java but i hope this site will help to clear my concepts. !!!!!
i hope i will take lot of knowledge from here..