A for Apple A for Apple -4 years ago 85
Java Question

Different Java behavior for Generics and Arrays

Why does java allows inconsistent type to be entered into a generic object reference but not in an array?

For Eg:

When initializing array:

int[] a = {1, 2, 3};


And, if I enter:

int[] a = {1, 2, "3"}; //Error for incompatible types


While for generics,

import java.util.ArrayList;

public class Test {
private static ArrayList tricky(ArrayList list) {
list.add(12345);
return list;
}
public static void main(String[] args) {
int i = 0;
ArrayList<String> list = new ArrayList();
list.add("String is King");
Test.tricky(list);
}
}


The above code will let you add any
Type
in the
list
object, resulting in a run time exception in some cases.

Why is there such a behavior?? Kindly give a proper explanation.

Answer Source

When you use the tricky method to insert data into your ArrayList Collection, it doesn't match the specified type i.e String, but still This is compatible because of Generics compatibility with older Legacy codes.

If it wouldn't have been for this i.e if it would have been the same way as of arrays, then all of the pre-java generic code would have been broken and all the codes would have to be re-written.

Remember one thing for generics, All your type-specifications are compile time restrictions, so when you use the tricky method to insert data in your list reference, what happens is the compiler thinks of it as a list to which ANYTHING apart from primitives can be added.

Only if you would have written this:

...
public class Test {
    private static ArrayList tricky(ArrayList<String> list) {
        list.add(12345); //Error, couldn't add Integer to String
        return list;
    }
...
}

I have written a documented post on this, Read here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download