Amazon

Friday, February 8, 2013

Java 6 Basics of Generics



//Below program is self explanatory. Please go through line by line and you will know basics of Generics


package com.sanjeev.generics;

import java.util.ArrayList;
import java.util.List;

public class Dog {

public static List getDogList(){
List list = new ArrayList();
list.add("hello dog"); //allowed as simple list can add any object
checkList(list); //allowed. For backward compatibility, normal list can be sent
                // as parameter to method with generic list
return list;     //same as above. Normal list can be returned in form of Generic List
}

public static List getDogList1(){
List list = new ArrayList(); //Defining Generic List.
list.add(new Dog());   //Allowed only Dog object, for which the list is made generic
checkList(list);       //Allowed method param, only Generic List for Dog Object
return list;
}

public static List getDogList2(){
List list = new ArrayList();
list.add("not allowed"); //Not allowed. Dog Object Generic List will not accept String to be added
checkList(list); //Allowed method param, only Generic List for Dog Object
return list; //Allowed. Genric list can be returned in Normal List
}

public static List doMyList(){
List < Object > myList = new ArrayList< Object >(); //Generic List for Object. Same as List myList = new ArrayList();
myList.add(new Dog()); //Can be added Dog object in Generic List of Object
checkList(myList);  //Not allowed. Generic List of < Object > cannot be sent as param in List
checkList1(myList); //Generic List< Object > can be sent in method param of List< Object >
checkList2(myList); //Generic List< Object > can be sent in method param of normal List

List  myList1 = new ArrayList();
myList1.add(new Dog()); //Allowed
checkList(myList1); //Normal list can be sent as param in any Genric List e.g. List
checkList1(myList1); //Normal list can be sent as param in any Genric List e.g. List< Object >
checkList2(myList1); //Normal List can be sent as param in any Normal List

List myList2 = new ArrayList();
myList.add(new Dog()); //Valid. Dog object can be added in Generic List
myList.add(new Object());//Valid. 'Object' can be added in Generic List
checkList(myList2);   //Valid. As Generic List being sent in parameter List
checkList1(myList2); //Not allowed. List cannot be sent as param in List< Object >
checkList2(myList2); //Allowed. List can be sent as param in normal List

return null;
}

public static void checkList(List mylist){
}

public static void checkList1(List< Object > mylist){
}

public static void checkList2(List mylist){
}
}

No comments:

Post a Comment

Amazon Best Sellors

Weblogic - Server Creation - Issues

Datasource creation using python script.  Python Script was failing after creating Datasource. From UI Admin Console, if I try to activat...