Junior — Middle
Are there any restrictions on using primitive types in generics?
sobes.tech AI
Answer from AI
In Java, generics work only with reference types, not with primitive types (int, boolean, double, etc.). This is because of type erasure during compilation, where information about the specific type is not retained in the bytecode.
Therefore, primitive types cannot be used directly as generic parameters. Instead, their wrapper classes are used, for example:
- int → Integer
- boolean → Boolean
- double → Double
Example:
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
If you need to work with primitives, you can use specialized collections from libraries (like Trove, FastUtil) or primitive streams (IntStream, etc.).