1

According to this post Java checks generics types only at run time but the same post's answer mentions that

Generics were introduced to the Java language to provide tighter type checks at compile time

I don't quite understand the answer there. Is the type check performed at compile time or at runtime?

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Address[] ad= new Address[3];
    ArrayList<Address> arr= new ArrayList<Address>();
    Employe e=new Employe(4, "harish");
    Address a = new Address();
    a.setOffice("SEX");
    ad[0]=a;
    arr.add(a);
    CopyOnWriteArrayList<Employe> c = new CopyOnWriteArrayList(arr);
    for(Employe em: c)System.out.println(e.getName());
    listimplementations v =new listimplementations();

}

From my code the collection<Address> is successfully added inside another collection<Employe> and I'm getting an error at runtime

Exception in thread "main" java.lang.ClassCastException: collection.Address 
cannot be cast to collection.Employe
at collection.listimplementations.main(listimplementations.java:26)

only during the for loop retrieval. I think this is because inside CopyOnWriteArrayList uses Object Array to store elements irrespective of generics type <Employe>.

  1. If <Employe> is effectively erased during compilation then how do generics provide tighter type checks at compile time ?
  2. Why is a compilation error not thrown during compile time for adding Address type inside Employe type collection?
amarnath harish
  • 945
  • 7
  • 24
  • 4
    Because you're using raw types. Generic type checks are done at compile-time. But `arr` is a raw type: it doesn't have any generic type. https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JB Nizet Jun 19 '18 at 17:58
  • i changed the code, im still getting error please check if this is what you mentioned. – amarnath harish Jun 19 '18 at 18:03
  • Also see https://stackoverflow.com/q/339699/2891664. – Radiodef Jun 19 '18 at 18:03
  • 2
    You're still using a raw type: `new CopyOnWriteArrayList(arr);` should be `new CopyOnWriteArrayList<>(arr);` or `new CopyOnWriteArrayList
    (arr);`, or `new CopyOnWriteArrayList(arr);`. None of them would then compile.
    – JB Nizet Jun 19 '18 at 18:08
  • please write this as answer i shall accept it. – amarnath harish Jun 19 '18 at 18:11
  • @amarnathharish if you are compiling on the command line, javac will tell you that you are using raw types, and suggest flags to add to see more verbose warnings; IDEs like eclipse or intellij will show warnings about raw types. Pay attention to warnings, they are there to help you! – Andy Turner Jun 19 '18 at 18:21

0 Answers0