I have a List that was initialised without any parameters. I added Map<String, Object> to that list.
Then I created a User object, and I know after typecasting the list to List<User> at compile time.
But I am surprised, I didn't get those errors at runtime either.
To give you an example the code is below:
I was expecting an error on the line
List<User> users = (List<User>) list;
Instead, the list users still remains a List<Map<String, Object>>
The following code runs perfectly fine.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class User {
    private String name;
    public String getName(){
        return name;
    }
}
public class Main {
    public static void main(String[] args) {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "Bruce");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "Clark");
        List list = List.of(map1, map2);
        List<User> users = (List<User>) list;
        System.out.println(users.get(0) instanceof Map);
    }
}
Output:
true
What am I missing here?
Also, I do get ClassCastException when I try to access the objects from the said users list.
For example, if I do users.get(0).getName() I get a nice ClassCastException
java.lang.ClassCastException: class java.util.HashMap cannot be cast to class User
But not before that.
So users.get(0) is still a HashMap
Can someone shine a light on why this happens?
 
     
    