Generics and arrays

 // Generic programming

// Find min value in Arrays

 

class Gen<T1 extends Comparable<T1>>

{

     T1 x[];

    

     Gen(T1 []v1)

     {

          x = v1;

     }

    

     public void fnDisplay()

     {

          System.out.println("Array elements");

          for(int i = 0;i<x.length;i++)

              System.out.println(x[i]);

     }

    

     public void fnFind()

     {

          T1 min = x[0];

          for(int i = 1;i<x.length;i++)

              if(x[i].compareTo(min) < 0 )

                   min = x[i];

             

          System.out.println("Minimum value in array = "+min);

     }

}

 


 

class Generics_Demo

{

     public static void main(String as[])

     {

          Integer [] ia = {8,4,2,6};

          Gen<Integer> g1 = new Gen<Integer>(ia);

          g1.fnDisplay(); 

          g1.fnFind();

         

          String []sa = {"cse", "it", "eee", "ece"};

          Gen<String> g2 = new Gen<String>(sa);

          g2.fnDisplay();

          g2.fnFind();

     }

}

Generics - Inheritance and constructors

 

// Generic programming

// Inheritance and constructors

 

class GenA<T1 extends Number>

{

     public T1 l, b;

     double area;

    

     GenA(T1 x, T1 y)

     {

          l = x;

          b = y;

     }

    

     public void fnArea()

     {

          area = l.doubleValue()*b.doubleValue();

          System.out.println("Area = "+area);

     }

}

 


 

class GenV<T1 extends Number> extends GenA<T1>

{

     T1 h;

     double vol;

    

     GenV(T1 x, T1 y, T1 z)

     {

          super(x,y);

          h = z;

     }

    

     public <T1 extends Number> void fnVol()

     {

          vol = l.doubleValue()*b.doubleValue()*h.doubleValue();

          System.out.println("Volume = "+vol);

     }

}

 

public class Generics_Demo

{

     public static void main(String as[])

     {  

          GenV<Double> g1 = new GenV<Double>(4.2,5.6,6.1);

          g1.fnArea();

          g1.fnVol();

     }

}

Generics - interfaces and arrays

 

// Example – Generic programming and Interface

// Minimum and Maximum element in an array

 

interface MinMax<T1 extends Comparable<T1>>

{

     public void fnMin();

     public void fnMax();

}

 

class Gen<T1 extends Comparable<T1>> implements MinMax<T1>

{

     T1 min, max;

     T1 [] Arr;

    

     Gen(T1 [] A)

     {

          Arr = A;

     }

    

     public void fnMin()

     {

          min = Arr[0];

          for(int i = 1;i<Arr.length;i++)

              if(Arr[i].compareTo(min) < 0 )

                   min = Arr[i];

     }

    

     public void fnMax()

     {

          max = Arr[0];

          for(int i = 1;i<Arr.length;i++)

              if(Arr[i].compareTo(max) > 0 )

                   max = Arr[i];

     }

    

 

     public void fnDisplay()

     {

          System.out.print("\n\nArray elements : ");

          for(int i = 0;i<Arr.length;i++)

              System.out.print(Arr[i]+"\t");

          System.out.print("\nMinimum element = "+min);

          System.out.print("\nMaximum element = "+max);

     }

}

 

public class Generics_Demo

{

     public static void main(String as[])

     {

          Integer [] A1 = {2,4,1,6,5,3};

          Double []A2 = {2.3, 5.6, 1.3, 4.3};

          String []A3 = {"CSE","IT","CIVIL","EEE","AUTO"};

         

          Gen<Integer> g1 = new Gen<Integer>(A1);

          g1.fnMin();

          g1.fnMax();

          g1.fnDisplay();

                  

          Gen<Double> g2 = new Gen<Double>(A2);

          g2.fnMin();

          g2.fnMax();

          g2.fnDisplay();

         

          Gen<String> g3 = new Gen<String>(A3);

          g3.fnMin();

          g3.fnMax();

          g3.fnDisplay();

     }

}

Generics - Bounded types

 Generics and Bounded types

Generics

Generics means parameterized types.

Parameterized types enable users to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter.

Using generics, it is possible to create classes that automatically work with different types of data.

A class, interface, or method that operates on a parameterized type is called generics.

// Generic programming – Example

// T1 – Type Parameter

// T1 – will be replaced by real type when object is created

 

class Gen<T1>

{

     T1 x;

    

     Gen(T1 v)

     {

          x = v;

     }

    

     public void fnDisplay()

     {

          System.out.println("x = "+x);

          System.out.println("Data type = "+x.getClass().getName());

     }

}

 

class Generics_Demo

{

     public static void main(String as[])

     {

          Gen<Integer> g1 = new Gen<Integer>(5);

          g1.fnDisplay(); 

         

          Gen<Double> g2 = new Gen<Double>(4.5);

          g2.fnDisplay(); 

         

          Gen<String> g3 = new Gen<String>("asd");

          g3.fnDisplay(); 

     }

}



Generics – Bounded Types

Sometimes it is useful to limit the types that can be passed to a type parameter. For example, a generic class that contains a method that returns the average of an array of numbers needs to restrict the data types to numeric data types only (integers, floats, and doubles). To handle such situations, Java provides bounded types. When specifying a type parameter, create an upper bound that declares the superclass from which all type arguments must be derived. This is accomplished through the use of an extends clause and / or interface type when specifying the type parameter, as shown here:

<T extends superclass>

<T extends superclass & interface>

 

// Generic programming

// Arrays - Bounded types

 

class Gen<T1 extends Number>

{

     T1 x[];

    

     Gen(T1 []v1)

     {

          x = v1;

     }

    

     public void fnDisplay()

     {

          System.out.println("Array elements");

          for(int i = 0;i<x.length;i++)

              System.out.println(x[i]);

     }

 

     public void fnAvg()

     {

          double sum = 0;

          for(int i = 0;i<x.length;i++)

              sum += x[i].doubleValue();

         

          System.out.println("Sum of elements = "+sum);

          System.out.println("Average of elements = "+(sum/x.length));

     }

}

 

class Generics_Demo

{

     public static void main(String as[])

     {

          Integer [] ia = {2,4,6,8};

          Gen<Integer> g1 = new Gen<Integer>(ia);

          g1.fnDisplay(); 

          g1.fnAvg();

     }

}


Restrictions in Generics

 

Some Generic Restrictions

There are a few restrictions when using generics in java programming. They involve

1.    creating objects of a type parameter,

2.    static members,

3.    exceptions,

4.    and arrays.

 

Type Parameters Can’t Be Instantiated

It is not possible to create an instance of a type parameter. For example, consider this class:

class Gen<T>

{

     T ob;

     Gen()

     {

ob = new T();    // Error

     }

}

Here, it is illegal to attempt to create an instance of T. The compiler does not know what type of object to create. T is simply a placeholder.

 

Restrictions on Static Members

No static member can use a type parameter declared by the enclosing class. For example, both of the static members of this class are illegal:

class Gen<T>

{

     static T obj;      // Error – no static variables of type T

 

     static T fnGet()      // Error – no static method can use T

     {

          return obj;

     }

}

 


 

Generic Array Restrictions

There are two important generics restrictions that apply to arrays.

1.    First, you cannot instantiate an array whose element type is a type parameter.

2.    Second, you cannot create an array of type-specific generic references.

 

// Generics and arrays – 1

class Gen<T extends Number>

{

     T Sum;

     T Arr [];

 

     Gen()

     {

          Arr = new T[5]; // Invalid

     }

}

class GArr

{

public static void main(String as[])

{

     // Error – cannot create an array of type–specific generic references.

     Gen<Integer> obj2[] = new Gen<Integer>[10];

}

}

 

Arr = new T[5] – is Invalid, since the compiler cannot determine what type of array to create.

 


 

// Generics and arrays – 2

class Gen<T extends Number>

{

     T Sum;

     T Arr [];

     Gen(T[] A)

     {

          Arr = A;  // Valid

     }

}

class GArr

{

public static void main(String as[])

{

     Integer N[] = {1,2,3};

     Gen<Integer> obj1 = new Gen<Integer>(N);

}

}

 

 

Generic Exception Restriction

A generic class cannot extend Throwable – so cannot create generic exception classes.