How to use Generics in Java
This simple example shows how to use Generics in Java.
Create a java class Employees:
public class Employees
{
private String name;
private int age;
public Employees(String n,int a)
{
name = n;
age = a;
}
public String ToString()
{
return name + ", " + age;
}
}
Create a java class Products:
public class Products
{
private String name;
private double price;
public Products(String n,double p)
{
name = n;
price = p;
}
public String ToString()
{
return name + " Euro " + price + "";
}
}
Create a java class GenericsTest:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class GenericsTest
{
public static void main (String [] args)
{
List<Employees> employeesList = new LinkedList<Employees>();
employeesList.add(new Employees("Zaira", 41));
employeesList.add(new Employees("Desy", 34));
employeesList.add(new Employees("Orny", 28));
employeesList.add(new Employees("Barbara", 31));
employeesList.add(new Employees("Elisa", 36));
List<Products> productsList = new LinkedList<Products>();
productsList.add(new Products("Server", 1300.99));
productsList.add(new Products("Desktop", 680.48));
productsList.add(new Products("Notebook", 560.34));
productsList.add(new Products("Netbook", 290.85));
System.out.println("List of employees:");
Iterator<Employees> itrEmployees = employeesList.iterator();
while(itrEmployees.hasNext()) {
Employees e =itrEmployees.next();
System.out.println(e.ToString());
}
System.out.println("---------------------------------------------");
System.out.println("List of products:");
Iterator<Products> itrProducts = productsList.iterator();
while(itrProducts.hasNext()) {
Products p =itrProducts.next();
System.out.println(p.ToString());
}
}
}
This is the output of the program:
List of employees:
Zaira, 41
Desy, 34
Orny, 28
Barbara, 31
Elisa, 36
---------------------------------------------
List of products:
Server Euro 1300.99
Desktop Euro 680.48
Notebook Euro 560.34
Netbook Euro 290.85
Category: Java