Arash Mahmoudi
Arash Mahmoudi

Reputation: 11

A generic stack does not accept integer values

Could someone please help me to find out why my generic stack does not accept integer values? I am receiving a compiling error indicating: unexpected type.

import java.util.Scanner;

public class Application {
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
    {
       int phoneNumber;
       int rightDigit;
       GenericStack<int> digits = new GenericStack<int>();

       System.out.print("Enter Your phone number: ");
       phoneNumber = sc.nextInt();

       while (phoneNumber !=0)
       {
          rightDigit = phoneNumber % 10;
          digits.push(rightDigit);
          phoneNumber /= 10;
       }

       System.out.print("Your phone number is: ");
       for(int i=0; i< digits.size(); i++)
       System.out.print(digits.get(i));
       System.out.println();
   }
}

And here is the generic stack class:

import java.util.LinkedList;

public class GenericStack<E> {

   private LinkedList<E> digitsList = new LinkedList<E>();

   public void push(E digit) {
      digitsList.addFirst(digit);
   }

   public int get(E index) {
      return digitsList.get(index);
   }
}

Any help would be appreciated.

Upvotes: 0

Views: 68

Answers (3)

Emmanuel Philip
Emmanuel Philip

Reputation: 11

The line has to be changed to

GenericStack<Integer> digits = new GenericStack<Integer>();

Here, Integer is an object wrapper class which is used to convert a primitive data type into an object

You might want to check out boxing and unboxing too to clear up your doubts.

Upvotes: 0

Noor Nawaz
Noor Nawaz

Reputation: 2225

It will not accept primitive, It will accept int Wrapper, Integer

GenericStack<Integer> digits = new GenericStack<Integer>();

Upvotes: 0

Dave Richardson
Dave Richardson

Reputation: 5005

In this line:

GenericStack<int> digits = new GenericStack<int>();

you need to use a class and not a primitive. Change int to Integer.

Upvotes: 1

Related Questions