DEV Community

Lalith Madhav
Lalith Madhav

Posted on

Do you know that List<int> is an error?

Recently found out that List, Set, Map doesn't accept primitive data types. Ok, since those are Interfaces(I think like this because they are different things) we get compiler errors. but what about arraylist, hashset, hashmap? aren't those classes. why don't they? let's get to know everything.
it is because in the older versions of java we could do

List a = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

and add

list.add("Java");
list.add(1.4);
Enter fullscreen mode Exit fullscreen mode

and made a lot of code. but on introducing generics the old code would be broken cuz the same arraylist which used to work then but doesn't work due to these generics. then the devs decided to make the complier such a way that on compiling the old code with old compiler gives same bytecode as compiling new code on new compiler which gives us int-> Integer, char->Character etc. this is the result of doing that. Because of this we have to declare the type of list like Integer, Boolean. It's also type safe ig.



List<Integer> integerList = new ArrayList<>();
List<Boolean> integerList = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)