-1

I want to get the elements from the list. I'm working right now on a project, next to the Class name is: <T extends Comparable<T>> written.

And I do have a ArrayList List<T> list = new ArrayList<>();

But how do I get an element out of the List? I tried list.get(1); but then I get a Error: error: incompatible types: T cannot be converted to int

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dean
  • 11
  • 3
  • 5
    You get the element exactly as you have written, but you must understand that the object you get is of type `T`, and not try to assign it to an `int` variable. – RealSkeptic Jun 17 '19 at 17:19
  • https://docs.oracle.com/javase/7/docs/api/java/util/List.html – Mitch Jun 17 '19 at 17:20

1 Answers1

2

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
}
Adam Kotwasinski
  • 4,377
  • 3
  • 17
  • 40