Why do we lose type safety when using List and not while using List<Object>? Aren’t they basically the same thing?
EDIT: I found that the following gives a compilation error
public class TestClass
{
static void func(List<Object> o, Object s){
o.add(s);
}
public static void main(String[] args){
func(new ArrayList<String>(), new Integer(1));
}
}
whereas this doesn’t
public class TestClass
{
static void func(List o, Object s){
o.add(s);
}
public static void main(String[] args){
func(new ArrayList<String>(), new Integer(1));
}
}
Why?
No they are not the same thing.
If you are providing an API,
and a client uses it improperly
then when your API specifies
List<Object>they get a compile-time error, but they don’t whenAPI.getList()returns aListandAPI.modifyList(list)takes aListwithout generic type parameters.EDIT:
In comments you mentioned changing
to
so that
would work.
That is violating type safety. The type-safe way to do this is
which is basically saying that
funcis a parameterized function that takes aListwhose type can be any super class of T, and a value of type T, and adds the value to the list.