Wednesday, November 13, 2019

Java List vs List<?> vs List<Object>

Before generics were introduced developers used lists as List which means you can store any type of objects including null inside it and when you read it you need to cast it
List list = new ArrayList();
list.add("String test");
list.add(new Date());

String s = (String) list.get(0);
From code above you can expect ClassCastException because if you try to assign 2nd item to String it will not succeed and you will get an exception during runtime. To prevent it you need to check if your type is correct and then cast as below