Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

Friday, October 16, 2015

Using Generic Collections

import java.util.*;

class GenericPractice{
    public static void main(String args[]){
        ArrayList<String> al=new ArrayList<String>();
        al.add(12);
        al.add("world");
        String s=(String)al.get(0);
        System.out.println(s);
        
    }
}

Creating Generic Type (class)

import java.util.*;

class Message<T>{
    private T msg;
    public void setMsg(T t){
        msg=t;
    }
    public T getMsg(){
        return msg;
    }
    public static void main(String[] args){
        
        Message<Object> m1=new Message<String>();
        m1.setMsg("Hello");
        String s1=m1.getMsg();
        System.out.println(s1);
        
        Message<Integer> m2=new Message<Integer>();
        m2.setMsg(12);
        int i=m2.getMsg();
        System.out.println(i);
    }
}

Examples of Generic Class, Interface, Method, Constructor


 1. Generics Class Example
public class Msg<T>
{
         public T t;
}
 
Msg<String> m1=new Msg<String>();
m1.t="Hello";

Msg<Integer> m2= new Msg<Integer>();
m2.t=5;


2. Generics Interface Example
public interface A1<T>
{
        public T m1();
}
 
public class B1 implements A1<String>{
        
        public String m1(){
 
        }
}
public class C1 implements A1<Rectangle>{
        public Rectangle m2(){
 
        }
}




3. Generic Constructor Example
class Sample {
  <T> Sample() {
              

               }
}

  Sample s1 = new <String> Sample();


4. Generic Method Example
static <T> void m1(T a, String s) {
    …
}

a1.m1(“hello”,”hi”);