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.

Java IO Streams

 

JAVA IO STREAMS

 

Streams
Java programs perform I/O operations through streams. A stream is a sequence of data. It is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams represent an input source and an output destination and they behave in the same manner, even if the actual physical devices to which they are linked differ.
 
Byte Streams and Character Streams
Java defines two types of streams: byte streams and character streams. Byte streams are used for handling binary data. Character streams are used for handling input and output of characters in Unicode.

 



IO STREAM

 

Byte streams
Byte streams are defined using two class hierarchies. At the top are two abstract classes InputStream and OutputStream. These two classes have several subclasses to handle different types of physical devices such as disk files, network connections, memory buffers etc., The most important methods of these classes are read() and write() for reading and writing bytes of data.

 



 BYTE STREAM

 

Character streams
Character streams are defined using two class hierarchies. At the top are two abstract classes Reader and Writer. These two classes handle Unicode character streams. The most important methods of these classes are read() and write() for reading and writing characters of data

 



 

CHARACTER STREAM


 

An example file handling program to demonstrate byte and character streams.
// Byte stream
// Using InputStream and OutputStream classes
// File copy program
/*
Note: Byte stream reads data from file in its ASCII form.
Typecast to char when writing to new file.
*/
import java.io.*;
import java.lang.*;
import java.util.*;
 
class IO_Demo
{
     public static void main(String as[]) throws IOException
     {
          FileInputStream fin = null;
          FileOutputStream fout = null;
          int i;
         
          try
          {
              fin = new FileInputStream("ipt.txt");
              fout = new FileOutputStream("opt.txt");
              while(true)
              {
                   i = fin.read();
                   if(i==-1)
                        break;
                   fout.write((char)i);                             
              }
          }
          catch(Exception e)
          {
              System.out.println(e);
          }
          finally
          {
              if(fin!=null)
                   fin.close();
              if(fout!=null)
                   fout.close();
              System.out.println("File copied.");
          }
     }
}
 
// Character stream
// Using Reader and Writer classes
// Read from console and write to file
 
import java.io.*;
 
class RW
{
     public static void main(String as[]) throws IOException
     {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          FileWriter fw = null;
          try
          {
              fw = new FileWriter("opt.txt");
              int i = 0;
              while(i<3)
              {
                   String str = br.readLine().trim();
                   fw.write(str+"\n");
                   i++;
              }
          }
 
          catch(Exception e)
          {
              System.out.println(e);
          }
          finally
          {
              if(fw!=null)
                   fw.close();  
              System.out.println("\nEnd of program.");
          }
     }
}