** Generics**
  • Through the use of generics, it is possible to create classes, interfaces, and methods that will work in a type-safe manner with various kinds of data.
  • Collections are called as group of objects and it define such several classes that lists maps and messages.
  • The generics added in collections are used for main function such as complete type safety .

Generics:

  • The term generics mean parameterized types.
  • Parameterized types can enable you to create class,methods in which type of data upon which they being operated as parameter.
  • Generics can create single class.

  • The line focus on auto unboxing feature

                                 int v =iob.getob().intvalue()
    
  • The auto unboxing makes the program more compact.

Generics work only with references:

  • In these type argument is passed on the type of parameter.But not passed to the type of primitive type(int,char)
  • Type wrappers are used to encapsulate the primitive type.

Generic Types differ based on the arguments:

  • The type of one arguments is not equal to the type of different argument.
  • Incase references are same but not passed in generics due to different primitive types(int ,char)
  • Its main aim is to prevent errors.
  • Example:

                       iOb = strOb; // Wrong!   (i & str are different in argument)
                       iob & str are belong to Gen class.
    

How Generic Improve Type Safety:

Example:

// NonGen is functionally equivalent to Gen
// but does not use generics.
class NonGen {
Object ob; // ob is now of type Object
// Pass the constructor a reference to
// an object of type Object
NonGen(Object o) {
ob = o;
}
// Return type Object.
Object getob() {
return ob;
}
// Show type of ob.
void showType() {
System.out.println("Type of ob is " +
ob.getClass().getName());
}
}
// Demonstrate the non-generic class.
class NonGenDemo {
public static void main(String args[]) {
NonGen iOb;
// Create NonGen Object and store
// an Integer in it. Autoboxing still occurs.
iOb = new NonGen(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value of iOb.
// This time, a cast is necessary.
int v = (Integer) iOb.getob();
System.out.println("value: " + v);
System.out.println();
// Create another NonGen object and
// store a String in it.
NonGen strOb = new NonGen("Non-Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb.
// Again, notice that a cast is necessary.String str = (String) strOb.getob();
System.out.println("value: " + str);
// This compiles, but is conceptually wrong!
iOb = strOb;
v = (Integer) iOb.getob(); // run-time error!
}
}

A Generic class with two parameters:

  • You can declare two type of parameter in a generic class or type.
  • Class TwoGen<T,V> {
  • Its T and V is separated by comma_separated Gens.
  • In these it has two type arguments and two type of parameters must be passed to GEN class.

The general form of Generic class:

  • Here it is full syntax for declaring a reference to generic class and instance creation,

    _ class-name&lt;type-args&gt;var-name= new class-name&lt;type-args&gt;cons-args-list._
    

Bounded Types:

  • Type parameters could be replaced by any type.
  • To use the class to obtain the average of array of any type of number as integers,float & doubles.
  • In these inums as integer and dnums as double are bounded per types.

Example:

Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
  • In addition of classtype as bound we can also use interface type

                class Gen&lt;T extends MyClass & MyInterface&gt; {
    
  • T is bounded by a class called MyClass and an interface called MyInterface.

  • Any type argument passed to T must be a subclass of MyClass and implement MyInterface.

Using Wildcard Arguments:

  • The preceding a section you want a add a same method called sameavg()
  • The sameavg() determine the two stats object yield the same average and no matter what type of objectholdsit.

Examples:

  • One object has integer and other has double values if the both average are same no matter sameavg()- are passed to other as stats()..

  • It work if the stats of integer type is passed only on parameter of ob as also stats of integer.

  • Its work only on narrow context.

  • The wildcard does not affect what type
    of stats objects can be created.

  • This is governed by the extends clause in the Stats declaration

Bounded Wildcards:

  • A bounded wildcard is especially important when you creating a generic type that will operate on class hierarchy.

Example:

// Two-dimensional coordinates.
class TwoD {
int x, y;
TwoD(int a, int b) {
x = a;
y = b;
}
}
// Three-dimensional coordinates.
class ThreeD extends TwoD {
int z;
ThreeD(int a, int b, int c) {
super(a, b);
z = c;
}
}
// Four-dimensional coordinates.
class FourD extends ThreeD {
int t;
FourD(int a, int b, int c, int d) {
super(a, b, c);
t = d;
}
}
  • 2D extends to 3D as XY
  • 3D extends to 4D as XYZ
  • 4D extends to time functions.
  • These coords bounded generic type specifies the Two() upper bound create a coords object will be the array of TwoDs() showXY.
  • The coords for three() bound to showXYZ.

  • These method is called bounded wildcart argument it helps you to prevent the object forming threeD & fourD .In these coords is an assigned value.

  • The most common bounded type is upper bound it is used to extends the clause.

  • suppose showXYZ method shows three X,Y,Z three set of coordinate variables.

Example2:

static void showXYZ(Coords<? extends ThreeD> c) {
System.out.println("X Y Z Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " +
c.coords[i].y + " " +
c.coords[i].z);
System.out.println();
}
  • Superclass it is the name of the class that serves in the upper bound.general form is shown,

       &lt;? extends superclass&gt;
    
  • You can also add lower bound for wildcart by adding a superclass in the wildcart declaration.

Creating a Generic Method:

  • Generic method is enclosed within a non-generic class.
static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
  • These type declared before the return type of the method.
  • T extends comparable <T>.These comparable define java.lang package.
  • The upper bound comparable determines the isIn() class as objects being compared.
  • next,V extends to T as it is upperbounded while V must have same type as T.
  • isIn() is a static member which used to enabling a independent object.

  • The type-param-list is comma-seperated list type of parameters.

Generic Constructors:

  • In these class is not generic but also its constructors belong to generic type.

Generic Interfaces:

  • In these generic class have generic methods and generic class but it also has an generic interfaces.

  • These interface obtain two benefits,

  • First ,It can be implemented for different types of data.

  • Second,It allows you to put constraints for the types of data which the interfaces can be implemented.

  • General Syntax,

                       interface=&gt;     _interface -name &lt;type-param-list&gt;_
    
  • Here a type param list is a comma-separated list of type of parameters.When a generic interface is implemented you must specify the type of argument

    class=&gt;   \_class-name &lt;type param-list&gt; \_implements \_interface name &lt;type-args-list&gt;\_
    

    Raw Types and Legacy Code:

  • Pre-generics code must be able to work with generics and the generics code must be able to work with pre-generics.

  • To handle this transition to generics,Java allows a generic class you without type of arguments.This is called raw type of class.
  • Its drawbacks are raw type of generic class is makes safety of generic is lost.

Generic class Hierarchies:

  • In these superclass and subclass are to be inherited by the generic type with same parameter type.
  • In these subclass Non generic is inherited by generic type.
  • Generic relates to the parameter type which is required by non generic.

Casting:

  • You can cast a single instance of generic class into another only if two are compatible and their type arguments are same.

Syntax:

(Gen<Integer>) iob2   //legal                because iob2 belongs to gen<integer>.
(Gen<long>)iob2       // Illegal             because iob2 belongs to gen<long>

Overriding a method in a generic class:

  • In these generic class can be overridden with any other method.

Example:

class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
System.out.print("Gen's getob(): " );
return ob;
}
}
// A subclass of Gen that overrides getob().
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
// Override getob().
T getob() {
System.out.print("Gen2's getob(): ");
return ob;
}
}
// Demonstrate generic method override.
class OverrideDemo {
public static void main(String args[]) {
// Create a Gen object for Integers.
Gen<Integer> iOb = new Gen<Integer>(88);
// Create a Gen2 object for Integers.
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
// Create a Gen2 object for Strings.
Gen2<String> strOb2 = new Gen2<String> ("Generics Test");
System.out.println(iOb.getob());
System.out.println(iOb2.getob());
System.out.println(strOb2.getob());
}
}
  • In these getob() is called as objects of type Gen2;

Type interference with generics:

  • The general form,

              myclass &lt;Integer,String&gt; myobj = new myclass&lt;Integer,String&gt;(98,"A String")
    
  • In these integer,string are the two arguments are specified when myobj is specified and new object created in myclass

  • In JDK7 the new clause the type of type argument is can be readily interfered from myobj2 than it specified second time.

  • Today's preceding condition the statements are shortened the quite long declarations.

  • The preceding conditions generalized when the interference is used when declaration syntax for generics and instance creation.

Erasure:

  • Java compiler is transforms your source code into object code.
  • General misunderstanding of process is important because it explains the features of surprising about the behavior.
  • Generic code has the compatible with the preexisting non generic code.
  • Any changes with syntax of the java language or JVM is used to break the older code.

  • When the java code is compiled then all generic type of information is removed

  • And replacing a type of bound is specified when the object explicit the no bound is required.

  • No type of parameter explicit at runtime in generics.

Ambiguity error:

  • The inclusion of generics give rise to a new type of error that you must guard against Ambiguity
  • The generic class has the same identical type for the both generics which leads to error.
  • Eg: In these t and v are having different types.

           T obj;
    
           V obj;
           Myclass <String,String> myobj = new Myclass<String,String>()
    
  • But in these myclass both type has the same string which leads to error.

  • In these Java determines a method to call by using number type,

    Myclass <String,Number> myobj = new Myclass<String,Number>()

  • But above cases can be used to obtain an object.

  • However same type as number can also leads to error.

      Myclass &lt;Number,Number&gt; myobj = new Myclass&lt;Number,Number&gt;()
    

Parameters can't be instantiated:

  • It is not possible to create a new type of t without the specific object because compiler cant understand which t and what object type.
  • It is illegal to create the instance of t.

Restrictions on static member:

  • No static member can use a type parameter which is declared by enclosed class.You can declare the static generic type can declare a class by its own parameters.
  • In which static member can be illegal when it is declared by enclosed class.

Generic array restrictions:

  • You cannot create an array of type to an specific generic references.
  • You cannot instantiate an array whose parameter is type parameter.(same generics type)

Example:

  • Vals = new T[10] (array of same type cant be instantiate)

Generic Exception Restriction:

  • A generic class cannot extend throwable.
  • You cannot create generic exception classes.

results matching ""

    No results matching ""