Let us see the compile time checking in java test with the below example.
Generics compile time checking example:
GenericsTest.java
import java.util.ArrayList; import java.util.List; /** * This class is used to show the compile time checking test. * @author w3schools */ public class GenericsTest { public static void main(String args[]){ //Arraylist without generics. List list1 = new ArrayList(); list1.add("Roxy"); list1.add("Sandy"); //No compile time error here //because no compile time checking is done. list1.add(new Integer(6)); //Arraylist with generics. List<String> list2 = new ArrayList<String>(); list2.add("Roxy"); list2.add("Sandy"); //Compile time error here //because we are adding a integer //in the string array list. list2.add(new Integer(6)); } } |
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(String) in the type List<String> is not applicable for the arguments (Integer) at com.w3schools.business.GenericsTest.main (GenericsTest.java:27) |
Download this example.
Next Topic: ClassCastException at runtime test.
Previous Topic: Generics terms and naming convention.