Generics provides a way to communicate the type of a
collection to the compiler. By this compiler can
maintain the consistency of collection at the time insertion and retrieval of an object. Before Generics
| After Generics
| ArrayList l = new ArrayList (); l.add("One"); l.add("Two");
//Type cast when you get element from Collection String str = (String) l.get(2);
System.out.println(str);
Iterator it = l.iterator();
while (it.hasNext()) { String val = (String) it.next();//Required type cast }
| ArrayList<String> l = new ArrayList<String>(); l.add("One"); l.add("Two");
//Do not type cast when get element from Collection String str = l.get(2);
System.out.println(str);
Iterator<String> it = l.iterator(); //specify type
while (it.hasNext()) { String val = it.next(); //No type cast }
| HashMap map = new HashMap ();
map.put(“1”,”One”); //Correct
| HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put(“1”,”One”); //Compilation Error |
Program :Step 1 - CodingCreate a text file c:\sunilos\TestGenerics.java and copy below contents.
import java.util.*;/* * A program of Generics. * copyright (c) sunilos Technologies Indore * @url : www.sunilos.co.in * */public class TestGenerics { public static void main(String[] args) { //Define a List and communicate its elements' data type to compiler ArrayList<String> l = new ArrayList<String>(); l.add("One"); l.add("Two"); l.add("Three"); l.add("Four"); l.add("Five"); String str = l.get(2); //No Type cast System.out.println(str); Iterator<String> it = l.iterator(); System.out.println("List elements ");
while (it.hasNext()) { System.out.println(it.next()); } //Define a Map and communicate its Key and Value data types to compiler HashMap<String,Integer> map = new HashMap<String,Integer>(); map.put("One", new Integer(1)); } }Step 2 - Deployment- Create a folder 'c:\sunilos'.
- Create or copy TestGenerics.java into 'c:\sunilos' folder.
- Open your command prompt and go to 'c:\sunilos'
- Compile TestGenerics.java with help of
- javac TestGenerics.java command. Compiled class file will be created in the same folder
- Congratulations!! your Control Statement Java program is ready to serve.
Step 3 - Testing- Make sure you are on Command Prompt under c:\sunilos directory
- Now start your Control Statements java program from command prompt with help of
- java TestGenerics command.
OutputThree List elements One Two Three Four Five <<Previous | Next>> |
 Updating...
Sunil Sahu, Oct 13, 2015, 4:27 AM
|