wam090
wam090

Reputation: 2873

Populating stack causes error

I'm populating a stack instance variable with elements of the array el, but in the line below it's giving me an error although I specified that it's a stack of Integers.

Error:

Incompatible types - found java.util.Stack but expected java.lang.Integer...

Code:

import java.util.Stack;

public class SortedStack
{
  private Stack<Integer> stack = new Stack<Integer>();

  public SortedStack(Integer[] el)
  {
      for(int i = 0; i < el.length; i++)
      {
          el[i] = stack;  /** THIS LINE*/
      }
  }
}

Upvotes: 2

Views: 304

Answers (5)

Tomas Aschan
Tomas Aschan

Reputation: 60664

To use a stack, you want to push() your item on top of it, and pop() it from the stack when you're ready to use it again. In your case, it seems more appropriate to inherit the stack, than to wrap it.

import java.util.Stack;

public class SortedStack extends Stack<Integer>
{    
  public SortedStack(Integer[] el) // Why "Sorted"? You're not sorting here...
  {
      for(int i = 0; i < el.length; i++)
      {
          this.push(el[i]);  /** THE ERROR IS THIS LINE */
      }
  }
}

Doing this, you can use your SortedStack just like any regular stack, with the addition of adding a whole range of elements in the constructor. You might also want to implement a PushRange() method, that can be called after the object is instantiated.

Upvotes: 0

Buhake Sindi
Buhake Sindi

Reputation: 89199

Use Stack.push() method.

stack.push(el[i]);

Upvotes: 0

Shekhar
Shekhar

Reputation: 11788

I think you want to add elements of el into stack . You were trying to assign stack object to el[i] which is not possible. Its obvious that you got error.

So your code should be like following :

public class SortedStack 
{ 
  private Stack<Integer> stack = new Stack<Integer>(); 

  public SortedStack(Integer[] el) 
  { 
      for(int i = 0; i < el.length; i++) 
      { 
          stack.push(el[i];
      } 
  } 
} 

Upvotes: 1

Ian
Ian

Reputation: 34529

I'm not a Java developer but I'm guessing if you want to put a value on the stack you'll need something like:

stack.push(el[i]);

The reason for your error is your trying to assign the i-th Element in an Integer array, to be a Stack. This is failing because it can't cast a Stack to an integer.

Upvotes: 0

mauris
mauris

Reputation: 43619

To add an item to the top of the stack, use the push method.

Example:

  public SortedStack(Integer[] el)
  {
      for(int i = 0; i < el.length; i++)
      {
          stack.push(el[i]);
      }
  }

This will push elements from the el array into the stack.

Upvotes: 3

Related Questions