Unboxing issues
Asked Answered
K

2

4

I have a class that extends the LinkedList class. Here's an excerpt of the code:

class SortedList<Integer> extends LinkedList<Integer> {
      int intMethod(Integer integerObject){
          return integerObject;
      }
}

This is expected to return the auto-unboxed int value. But for some reason, the compiler throws an error that says that the types are incompatible and that the required type was int and the type found was Integer. This works in a different class perfectly fine! What gives? :(

Karrah answered 6/2, 2011 at 7:30 Comment(0)
A
11

This is because you have <Integer> after SortedList.

Usually you use T for type parameters: class SortedList<T>, but you used Integer instead. That is, you made Integer a type parameter (which shadows the java.lang.Integer).

Your class, as it stands, is equivalent to

class SortedList<T> extends LinkedList<T> {
      int intMethod(T integerObject){
          return integerObject;         // <--  "Cannot convert from T to int"
      }
}

Remove the type parameter and it works just fine:

class SortedList extends LinkedList<Integer> {
      int intMethod(Integer integerObject){
          return integerObject;
      }
}
Armin answered 6/2, 2011 at 7:35 Comment(0)
S
2

The problem is that you've declared Integer as a generic type parameter for the SortedList class. So when you refer to Integer as a parameter of the intMethod method, that means the type parameter, not the java.lang.Integer type which I suspect you meant. I think you want:

class SortedList extends LinkedList<Integer> {
    int intMethod(Integer integerObject){
        return integerObject;
    }
}

This way a SortedList is always a list of integers, which I suspect is what you were trying to achieve. If you did want to make SortedList a generic type, you would probably want:

class SortedList<T> extends LinkedList<T> {
    int intMethod(Integer integerObject){
        return integerObject;
    }
}
Swage answered 6/2, 2011 at 7:36 Comment(1)
thank you, that worked very well. I knew I should have read up on generics before messing with that. Serves me right. :)Karrah

© 2022 - 2024 — McMap. All rights reserved.