Search code examples
javawrapperprimitive

Unable to convert from int to Integer in Java


I have an Integer Stack and I'm working on a method to insert elements into it from a JOptionPane. However, JOptionPane returns a string, so I parsed it into an int, but then I tried to insert the value in the stack and apparently, I need to convert it from int to Integer first.

So I tried with what every guide has been mentioning, create a new Integer object with the value of the parsedInt, but I'm getting error

"unexpected type
  required: class
  found:    type parameter Integer
  where Integer is a type-variable:
    Integer extends Object declared in class SizedStack"

This is the code I'm trying

public void addToStack(JOptionPane optionPane) {
    int val;
    String temp;
    temp = optionPane.showInputDialog("Enter an integer to insert into the stack");
    val = parseInt(temp);
    Integer valInteger = new Integer(val);
    this.push(valInteger);
}

line Integer valInteger = new Integer(val); is the one flagging the error.

Any ideas what's wrong?


Solution

  • Looks like you've declared your class similar to:

    class SizedStack<Integer> {
    

    Integer is now a type variable, not the class java.lang.Integer.

    If you want it to be a generic class, write it something like:

    class SizedStack<T> {
    

    Or for an Integer-only stack.

    class SizedStack {
    

    If it is an Integer-only stack implementing a generic stack.

    class SizedStack implements Stack<Integer> {