In: Computer Science
Give an example of a program that uses the nongeneric version of a class from the STL and the equivalent program that uses the generic version. How do the two implementations differ? Why is having the syntax of generics better?
Source Code in Java:
import java.util.ArrayList;
class NonGeneric
{
public static void main(String[] args)
{
ArrayList a=new ArrayList(); //creating object of ArrayList
//adding two elements to the ArrayList
a.add("Debjit");
a.add("Ganguli");
//calling get() to get the elements
String s1=(String)a.get(0);
String s2=(String)a.get(1);
//printing the elements
System.out.println(s1+" "+s2);
}
}
import java.util.ArrayList;
class Generic
{
public static void main(String[] args)
{
ArrayList<String> a=new ArrayList<String>(); //creating
object of ArrayList for String elements
//adding two elements to the ArrayList
a.add("Debjit");
a.add("Ganguli");
//calling get() to get the elements
String s1=a.get(0);
String s2=a.get(1);
//printing the elements
System.out.println(s1+" "+s2);
}
}
Output:
The two implementations differ in that Generic class requires a type to be called, whereas Non-generic class does not.
The advantages of Generic classes are: