You cannot declare
List<int> list = ...
but you can safely declare
List<Integer> list = new ArrayList<>()
Integer
class matches the required signature (it implements Comparable<Integer>
).
So when you do this, it's okay to do
List<Integer> list = new ArrayList<>()
list.add(13) // autoboxing converts int to Integer
int value = list.get(0) // autoboxing converts Integer back to int
As an extra note, please remember that it's possible to add null
-s to that list, so the following will explode with NPE:
List<Integer> list = new ArrayList<>()
list.add(null) // null reference is okay
int value = list.get(0) // throws, we got null Integer reference,
// that cannot be converted to a primitive
If you ever have a need to do this, you can do:
Integer value = list.get(0)
if (null != value) {
int primitive = value // safe, because non-null
}