Stacks and ArrayList

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mia023
    New Member
    • May 2007
    • 89

    Stacks and ArrayList

    Hello everyone.



    Assume that we have previously defined the following class StockPurchase that has the following as instance variables
    a) The name of the stock (a string)
    b) The number of shares of a stock (an int)
    c) The purchase price (can be a decimal)



    Part-2) Write a class called ManageMultipleS tocks and its corresponding driver. Your program should allow the user to enter information about purchases of various stocks: their names, the amount of shares, and the prices. The user can then enter a query about the cost of a given stock according to the LIFO or FIFO accounting methods for a certain number of shares.
    The ManageMultipleS tocks could have the following methods:
    void addStockPurchas e(StockPurchase sp);
    double getLIFOCost(Str ing stockName, int numShares);
    double getFIFOCost(Str ing stockName, int numShares);

    Hint: ManageMultipleS tocks will have a collection of stacks (a Vector or ArrayList of ObjectStack) and a collection of queues (a Vector or ArrayList of ObjectQueue). You might also have ManageMultipleS tocks contain a collection of ManageSingleSto ck objects.







    My question is just an explaination of the problem and why do we need to use ArrayList here and in addStockPurchas e(StockPurchase sp) do we have to do ArrayList list=new ArrayList();
    list.add(sp);


    I don't need the code I just need an explaination for the problem.
  • mia023
    New Member
    • May 2007
    • 89

    #2
    Originally posted by mia023
    Hello everyone.



    Assume that we have previously defined the following class StockPurchase that has the following as instance variables
    a) The name of the stock (a string)
    b) The number of shares of a stock (an int)
    c) The purchase price (can be a decimal)



    Part-2) Write a class called ManageMultipleS tocks and its corresponding driver. Your program should allow the user to enter information about purchases of various stocks: their names, the amount of shares, and the prices. The user can then enter a query about the cost of a given stock according to the LIFO or FIFO accounting methods for a certain number of shares.
    The ManageMultipleS tocks could have the following methods:
    void addStockPurchas e(StockPurchase sp);
    double getLIFOCost(Str ing stockName, int numShares);
    double getFIFOCost(Str ing stockName, int numShares);

    Hint: ManageMultipleS tocks will have a collection of stacks (a Vector or ArrayList of ObjectStack) and a collection of queues (a Vector or ArrayList of ObjectQueue). You might also have ManageMultipleS tocks contain a collection of ManageSingleSto ck objects.







    My question is just an explaination of the problem and why do we need to use ArrayList here and in addStockPurchas e(StockPurchase sp) do we have to do ArrayList list=new ArrayList();
    list.add(sp);


    I don't need the code I just need an explaination for the problem.
    Any suggestions or help is also helpful!!

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      You need those two lines first to initialize the ArrayList so it can be used and second to add the object to the list. That said, I question why the first line is in the method rather than the constructor, where it belongs.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        A few points to look up and read about are :
        ArrayList vs array
        ArrayList vs Vector

        Google for those. They should be a good starting point.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by Laharl
          You need those two lines first to initialize the ArrayList so it can be used and second to add the object to the list. That said, I question why the first line is in the method rather than the constructor, where it belongs.
          I'm afraid that when this thread really gets started the OP simply tries to add
          those few magical lines here and there in the code and then come back here.
          I hope I'm wrong ...

          kind regards,

          Jos

          Comment

          • mia023
            New Member
            • May 2007
            • 89

            #6
            Originally posted by JosAH
            I'm afraid that when this thread really gets started the OP simply tries to add
            those few magical lines here and there in the code and then come back here.
            I hope I'm wrong ...

            kind regards,

            Jos
            I didn't understand what should be done

            Comment

            • mia023
              New Member
              • May 2007
              • 89

              #7
              Originally posted by mia023
              I didn't understand what should be done
              [code=java]]import java.util.*;
              public class ManageSingleSto ck{
              ObjectStack stack;

              public ManageSingleSto ck(){ //constructor
              stack=new ObjectStack();
              }

              public void addStockPurchas e(StockPurchase sp){ //add
              stack.push(sp);
              }

              public double getLIFOCost(int num_shares){ //stack
              double cost = 0;
              int num_needed = num_shares;

              while(num_neede d > 0){ //loop until remaining shares needed not equals to zero

              StockPurchase sp = (StockPurchase) stack.peek();

              if(num_needed >= sp.numOfshares) { //case where we need shares more than the available shares in peek()
              cost += sp.numOfshares* sp.purchase_pri ce;
              num_needed -= sp.numOfshares;
              stack.pop();
              }
              else{ //case where we need shares less than the available shares in peek()
              cost += num_needed*sp.p urchase_price;
              sp.numOfshares -= num_needed;
              num_needed = 0;
              }
              }

              cost = cost/num_shares; //calculate the average cost

              return cost;
              }

              public double getFIFOCost(int num_shares){ //queue
              double cost = 0;
              int num_needed = num_shares;

              ObjectStack stack1 = new ObjectStack();

              //stack the stack => queue
              while(!stack.is Empty())
              stack1.push(sta ck.pop());

              //same like before
              while(num_neede d > 0){

              StockPurchase sp = (StockPurchase) stack1.peek();

              if(num_needed >= sp.numOfshares) {
              cost += sp.numOfshares* sp.purchase_pri ce;
              num_needed -= sp.numOfshares;
              stack.pop();
              }
              else{
              cost += num_needed*sp.p urchase_price;
              sp.numOfshares -= num_needed;
              num_needed = 0;
              }
              }

              cost = cost/num_shares;

              //stack the queue => stack
              while(!stack1.i sEmpty())
              stack.push(stac k1.pop());

              return cost;
              }

              public String toString(){
              stack.trimToSiz e();
              return stack.toString( );
              }

              public static void main(String[]args){
              ManageSingleSto ck st=new ManageSingleSto ck();
              Scanner in=new Scanner(System. in);
              st.addStockPurc hase( new StockPurchase(" A", 100, 500));
              st.addStockPurc hase( new StockPurchase(" B", 3, 1000));
              st.addStockPurc hase( new StockPurchase(" C", 4, 250));
              System.out.prin t("Do you want to getFIFOCOST(Pre ss 1) or getLIFOCOST(Pre ss 2) ?");
              int num=in.nextInt( );
              System.out.prin tln();
              if(num==1){
              double x =st.getFIFOCost (5);
              System.out.prin tln("FIFO:\t" +x );
              System.out.prin tln(st);
              }
              if(num==2){
              double y=st.getLIFOCos t(5);
              System.out.prin tln("LIFO:\t"+y );
              System.out.prin tln(st);
              }
              }
              }[/code]
              This is my code but one a single stock
              Last edited by JosAH; May 20 '08, 04:25 PM. Reason: fixed the [code] ... [/code] tags

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                So what is your ObjectStack class like?

                kind regards,

                Jos

                Comment

                • mia023
                  New Member
                  • May 2007
                  • 89

                  #9
                  Originally posted by JosAH
                  So what is your ObjectStack class like?

                  kind regards,

                  Jos
                  import java.util.Empty StackException;

                  /*************** *************** *************** *************** *************** ***
                  * An <CODE>ObjectSta ck</CODE> is a stack of references to objects.
                  *
                  * <dl><dt><b>Limi tations:</b>
                  * <dd>
                  * (1) The capacity of one of these stacks can change after it's created, but
                  * the maximum capacity is limited by the amount of free memory on the
                  * machine. The constructor, <CODE>ensureCap acity</CODE>, <CODE>push</CODE>,
                  * and <CODE>trimToSiz e</CODE> will result in an
                  * <CODE>OutOfMemo ryError</CODE> when free memory is exhausted.
                  * <dd>
                  * (2) A stack's capacity cannot exceed the maximum integer 2,147,483,647
                  * (<CODE>Integer. MAX_VALUE</CODE>). Any attempt to create a larger capacity
                  * results in a failure due to an arithmetic overflow.
                  * </dl>
                  *
                  * <dt><b>Java Source Code for this class:</b><dd>
                  * <A HREF="../edu/colorado/collections/ObjectStack.jav a">
                  * http://www.cs.colorado .edu/~main/edu/colorado/collections/ObjectStack.jav a
                  * </A>
                  *
                  * @author Michael Main
                  * <A HREF="mailto:ma in@colorado.edu "> (main@colorado. edu) </A>
                  *
                  * @version
                  * Jun 12, 1998
                  *
                  * @see ObjectLinkedSta ck
                  * @see BooleanStack
                  * @see ByteStack
                  * @see CharStack
                  * @see DoubleStack
                  * @see FloatStack
                  * @see IntStack
                  * @see LongStack
                  * @see ShortStack
                  *************** *************** *************** *************** *************** ***/
                  public class ObjectStack implements Cloneable
                  {
                  // Invariant of the ObjectStack class:
                  // 1. The number of items in the stack is in the instance variable manyItems.
                  // 2. For an empty stack, we do not care what is stored in any of data; for a
                  // non-empty stack, the items in the stack are stored in a partially-filled array called
                  // data, with the bottom of the stack at data[0], the next item at data[1], and so on
                  // to the top of the stack at data[manyItems-1].
                  private Object[ ] data;
                  private int manyItems;


                  /**
                  * Initialize an empty stack with an initial capacity of 10. Note that the
                  * <CODE>push</CODE> method works efficiently (without needing more
                  * memory) until this capacity is reached.
                  * @param - none
                  * <dt><b>Postcond ition:</b><dd>
                  * This stack is empty and has an initial capacity of 10.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for:
                  * <CODE>new Object[10]</CODE>.
                  **/
                  public ObjectStack( )
                  {
                  final int INITIAL_CAPACIT Y = 10;
                  manyItems = 0;
                  data = new Object[INITIAL_CAPACIT Y];
                  }


                  /**
                  * Initialize an empty stack with a specified initial capacity. Note that the
                  * <CODE>push</CODE> method works efficiently (without needing more
                  * memory) until this capacity is reached.
                  * @param <CODE>initialCa pacity</CODE>
                  * the initial capacity of this stack
                  * <dt><b>Precondi tion:</b><dd>
                  * <CODE>initialCa pacity</CODE> is non-negative.
                  * <dt><b>Postcond ition:</b><dd>
                  * This stack is empty and has the given initial capacity.
                  * @exception IllegalArgument Exception
                  * Indicates that initialCapacity is negative.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for:
                  * <CODE>new Object[initialCapacity]</CODE>.
                  **/
                  public ObjectStack(int initialCapacity )
                  {
                  if (initialCapacit y < 0)
                  throw new IllegalArgument Exception
                  ("initialCapaci ty too small " + initialCapacity );
                  manyItems = 0;
                  data = new Object[initialCapacity];
                  }


                  /**
                  * Generate a copy of this stack.
                  * @param - none
                  * @return
                  * The return value is a copy of this stack. Subsequent changes to the
                  * copy will not affect the original, nor vice versa. Note that the return
                  * value must be type cast to an <CODE>ObjectSta ck</CODE> before it can be used.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for creating the clone.
                  **/
                  public Object clone( )
                  { // Clone an ObjectStack.
                  ObjectStack answer;

                  try
                  {
                  answer = (ObjectStack) super.clone( );
                  }
                  catch (CloneNotSuppor tedException e)
                  {
                  // This exception should not occur. But if it does, it would probably indicate a
                  // programming error that made super.clone unavailable. The most comon error
                  // The most common error would be forgetting the "Implements Cloneable"
                  // clause at the start of this class.
                  throw new RuntimeExceptio n
                  ("This class does not implement Cloneable");
                  }

                  answer.data = (Object [ ]) data.clone( );

                  return answer;
                  }


                  /**
                  * Change the current capacity of this stack.
                  * @param <CODE>minimumCa pacity</CODE>
                  * the new capacity for this stack
                  * <dt><b>Postcond ition:</b><dd>
                  * This stack's capacity has been changed to at least <CODE>minimumCa pacity</CODE>.
                  * If the capacity was already at or greater than <CODE>minimumCa pacity</CODE>,
                  * then the capacity is left unchanged.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for: <CODE>new Object[minimumCapacity]</CODE>.
                  **/
                  public void ensureCapacity( int minimumCapacity )
                  {
                  Object biggerArray[ ];

                  if (data.length < minimumCapacity )
                  {
                  biggerArray = new Object[minimumCapacity];
                  System.arraycop y(data, 0, biggerArray, 0, manyItems);
                  data = biggerArray;
                  }
                  }


                  /**
                  * Accessor method to get the current capacity of this stack.
                  * The <CODE>push</CODE> method works efficiently (without needing
                  * more memory) until this capacity is reached.
                  * @param - none
                  * @return
                  * the current capacity of this stack
                  **/
                  public int getCapacity( )
                  {
                  return data.length;
                  }


                  /**
                  * Determine whether this stack is empty.
                  * @param - none
                  * @return
                  * <CODE>true</CODE> if this stack is empty;
                  * <CODE>false</CODE> otherwise.
                  **/
                  public boolean isEmpty( )
                  {
                  return (manyItems == 0);
                  }


                  /**
                  * Get the top item of this stack, without removing the item.
                  * @param - none
                  * <dt><b>Precondi tion:</b><dd>
                  * This stack is not empty.
                  * @return
                  * the top item of the stack
                  * @exception EmptyStackExcep tion
                  * Indicates that this stack is empty.
                  **/
                  public Object peek( )
                  {
                  if (manyItems == 0)
                  // EmptyStackExcep tion is from java.util and its constructor has no argument.
                  throw new EmptyStackExcep tion( );
                  return data[manyItems-1];
                  }


                  /**
                  * Get the top item, removing it from this stack.
                  * @param - none
                  * <dt><b>Precondi tion:</b><dd>
                  * This stack is not empty.
                  * <dt><b>Postcond ition:</b><dd>
                  * The return value is the top item of this stack, and the item has
                  * been removed.
                  * @exception EmptyStackExcep tion
                  * Indicates that this stack is empty.
                  **/
                  public Object pop( )
                  {
                  if (manyItems == 0)
                  // EmptyStackExcep tion is from java.util and its constructor has no argument.
                  throw new EmptyStackExcep tion( );
                  return data[--manyItems];
                  }


                  /**
                  * Push a new item onto this stack. If the addition
                  * would take this stack beyond its current capacity, then the capacity is
                  * increased before adding the new item. The new item may be the null
                  * reference.
                  * @param <CODE>item</CODE>
                  * the item to be pushed onto this stack
                  * <dt><b>Postcond ition:</b><dd>
                  * The item has been pushed onto this stack.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for increasing the stack's capacity.
                  * <dt><b>Note:</b><dd>
                  * An attempt to increase the capacity beyond
                  * <CODE>Integer.M AX_VALUE</CODE> will cause the stack to fail with an
                  * arithmetic overflow.
                  **/
                  public void push(Object item)
                  {
                  if (manyItems == data.length)
                  {
                  // Double the capacity and add 1; this works even if manyItems is 0. However, in
                  // case that manyItems*2 + 1 is beyond Integer.MAX_VAL UE, there will be an
                  // arithmetic overflow and the bag will fail.
                  ensureCapacity( manyItems*2 + 1);
                  }
                  data[manyItems] = item;
                  manyItems++;
                  }


                  /**
                  * Accessor method to determine the number of items in this stack.
                  * @param - none
                  * @return
                  * the number of items in this stack
                  **/
                  public int size( )
                  {
                  return manyItems;
                  }


                  /**
                  * Reduce the current capacity of this stack to its actual size (i.e., the
                  * number of items it contains).
                  * @param - none
                  * <dt><b>Postcond ition:</b><dd>
                  * This stack's capacity has been changed to its current size.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for altering the capacity.
                  **/
                  public void trimToSize( )
                  {
                  Object trimmedArray[ ];

                  if (data.length != manyItems)
                  {
                  trimmedArray = new Object[manyItems];
                  System.arraycop y(data, 0, trimmedArray, 0, manyItems);
                  data = trimmedArray;
                  }
                  }
                  public String toString(){
                  String s = "";
                  for(int i=0;i<data.leng th;i++){
                  s+=data[i]+" , ";
                  }
                  return "[ " + s + "]";
                  }

                  }




























                  import java.util.NoSuc hElementExcepti on;

                  /*************** *************** *************** *************** *************** ***
                  * An <CODE>ObjectQue ue</CODE> is a queue of references to objects.
                  *
                  * <dl><dt><b>Limi tations:</b>
                  * <dd>
                  * (1) The capacity of one of these queues can change after it's created, but
                  * the maximum capacity is limited by the amount of free memory on the
                  * machine. The constructor, <CODE>add</CODE>, <CODE>clone</CODE>,
                  * and <CODE>union</CODE> will result in an
                  * <CODE>OutOfMemo ryError</CODE> when free memory is exhausted.
                  * <dd>
                  * (2) A queue's capacity cannot exceed the maximum integer 2,147,483,647
                  * (<CODE>Integer. MAX_VALUE</CODE>). Any attempt to create a larger capacity
                  * results in a failure due to an arithmetic overflow.
                  * </dl>
                  *
                  * <dt><b>Java Source Code for this class:</b><dd>
                  * <A HREF="../edu/colorado/collections/ObjectQueue.jav a">
                  * http://www.cs.colorado .edu/~main/edu/colorado/collections/ObjectQueue.jav a
                  * </A>
                  *
                  * @author Michael Main
                  * <A HREF="mailto:ma in@colorado.edu "> (main@colorado. edu) </A>
                  *
                  * @version
                  * Jun 12, 1998
                  *
                  * @see ObjectLinkedQue ue
                  * @see BooleanQueue
                  * @see ByteQueue
                  * @see CharQueue
                  * @see DoubleQueue
                  * @see FloatQueue
                  * @see IntQueue
                  * @see LongQueue
                  * @see ShortQueue
                  *************** *************** *************** *************** *************** ***/
                  public class ObjectQueue implements Cloneable
                  {
                  // Invariant of the ObjectQueue class:
                  // 1. The number of items in the queue is in the instance variable manyItems.
                  // 2. For a non-empty queue, the items are stored in a circular array
                  // beginning at data[front] and continuing through data[rear].
                  // 3. For an empty queue, manyItems is zero and data is a reference to an
                  // array, but we don't care about front and rear.
                  private Object[ ] data;
                  private int manyItems;
                  private int front;
                  private int rear;


                  /**
                  * Initialize an empty queue with an initial capacity of 10. Note that the
                  * <CODE>insert</CODE> method works efficiently (without needing more
                  * memory) until this capacity is reached.
                  * @param - none
                  * <dt><b>Postcond ition:</b><dd>
                  * This queue is empty and has an initial capacity of 10.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for:
                  * <CODE>new Object[10]</CODE>.
                  **/
                  public ObjectQueue( )
                  {
                  final int INITIAL_CAPACIT Y = 10;
                  manyItems = 0;
                  data = new Object[INITIAL_CAPACIT Y];
                  // We don't care about front and rear for an empty queue.
                  }


                  /**
                  * Initialize an empty queue with a specified initial capacity. Note that the
                  * <CODE>insert</CODE> method works efficiently (without needing more
                  * memory) until this capacity is reached.
                  * @param <CODE>initialCa pacity</CODE>
                  * the initial capacity of this queue
                  * <dt><b>Precondi tion:</b><dd>
                  * <CODE>initialCa pacity</CODE> is non-negative.
                  * <dt><b>Postcond ition:</b><dd>
                  * This queue is empty and has the given initial capacity.
                  * @exception IllegalArgument Exception
                  * Indicates that initialCapacity is negative.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for:
                  * <CODE>new Object[initialCapacity]</CODE>.
                  **/
                  public ObjectQueue(int initialCapacity )
                  {
                  if (initialCapacit y < 0)
                  throw new IllegalArgument Exception
                  ("initialCapaci ty is negative: " + initialCapacity );
                  manyItems = 0;
                  data = new Object[initialCapacity];
                  // We don't care about front and rear for an empty queue.
                  }


                  /**
                  * Generate a copy of this queue.
                  * @param - none
                  * @return
                  * The return value is a copy of this queue. Subsequent changes to the
                  * copy will not affect the original, nor vice versa. Note that the return
                  * value must be type cast to an <CODE>ObjectQue ue</CODE> before it can be used.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for creating the clone.
                  **/
                  public Object clone( )
                  { // Clone an ObjectQueue.
                  ObjectQueue answer;

                  try
                  {
                  answer = (ObjectQueue) super.clone( );
                  }
                  catch (CloneNotSuppor tedException e)
                  {
                  // This exception should not occur. But if it does, it would probably indicate a
                  // programming error that made super.clone unavailable. The most comon error
                  // The most common error would be forgetting the "Implements Cloneable"
                  // clause at the start of this class.
                  throw new RuntimeExceptio n
                  ("This class does not implement Cloneable");
                  }

                  answer.data = (Object [ ]) data.clone( );

                  return answer;
                  }


                  /**
                  * Change the current capacity of this queue.
                  * @param <CODE>minimumCa pacity</CODE>
                  * the new capacity for this queue
                  * <dt><b>Postcond ition:</b><dd>
                  * This queue's capacity has been changed to at least <CODE>minimumCa pacity</CODE>.
                  * If the capacity was already at or greater than <CODE>minimumCa pacity</CODE>,
                  * then the capacity is left unchanged.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for: <CODE>new Object[minimumCapacity]</CODE>.
                  **/
                  public void ensureCapacity( int minimumCapacity )
                  {
                  Object biggerArray[ ];
                  int n1, n2;

                  if (data.length >= minimumCapacity )
                  // No change needed.
                  return;
                  else if (manyItems == 0)
                  // Just increase the size of the array because the queue is empty.
                  data = new Object[minimumCapacity];
                  else if (front <= rear)
                  { // Create larger array and copy data[front]...data[rear] into it.
                  biggerArray = new Object[minimumCapacity];
                  System.arraycop y(data, front, biggerArray, front, manyItems);
                  data = biggerArray;
                  }
                  else
                  { // Create a bigger array, but be careful about copying items into it. The queue items
                  // occur in two segments. The first segment goes from data[front] to the end of the
                  // array, and the second segment goes from data[0] to data[rear]. The variables n1
                  // and n2 will be set to the number of items in these two segments. We will copy
                  // these segments to biggerArray[0...manyItems-1].
                  biggerArray = new Object[minimumCapacity];
                  n1 = data.length - front;
                  n2 = rear + 1;
                  System.arraycop y(data, front, biggerArray, 0, n1);
                  System.arraycop y(data, 0, biggerArray, n1, n2);
                  front = 0;
                  rear = manyItems-1;
                  data = biggerArray;
                  }
                  }


                  /**
                  * Accessor method to get the current capacity of this queue.
                  * The <CODE>insert</CODE> method works efficiently (without needing
                  * more memory) until this capacity is reached.
                  * @param - none
                  * @return
                  * the current capacity of this queue
                  **/
                  public int getCapacity( )
                  {
                  return data.length;
                  }


                  /**
                  * Get the front item, removing it from this queue.
                  * @param - none
                  * <dt><b>Precondi tion:</b><dd>
                  * This queue is not empty.
                  * <dt><b>Postcond ition:</b><dd>
                  * The return value is the front item of this queue, and the item has
                  * been removed.
                  * @exception NoSuchElementEx ception
                  * Indicates that this queue is empty.
                  **/
                  public Object getFront( )
                  {
                  Object answer;

                  if (manyItems == 0)
                  throw new NoSuchElementEx ception("Queue underflow");
                  answer = data[front];
                  front = nextIndex(front );
                  manyItems--;
                  return answer;
                  }


                  /**
                  * Insert a new item in this queue. If the addition
                  * would take this queue beyond its current capacity, then the capacity is
                  * increased before adding the new item. The new item may be the null
                  * reference.
                  * @param <CODE>item</CODE>
                  * the item to be pushed onto this queue
                  * <dt><b>Postcond ition:</b><dd>
                  * The item has been pushed onto this queue.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for increasing the queue's capacity.
                  * <dt><b>Note:</b><dd>
                  * An attempt to increase the capacity beyond
                  * <CODE>Integer.M AX_VALUE</CODE> will cause the queue to fail with an
                  * arithmetic overflow.
                  **/
                  public void insert(Object item)
                  {
                  if (manyItems == data.length)
                  {
                  // Double the capacity and add 1; this works even if manyItems is 0. However, in
                  // case that manyItems*2 + 1 is beyond Integer.MAX_VAL UE, there will be an
                  // arithmetic overflow and the bag will fail.
                  ensureCapacity( manyItems*2 + 1);
                  }

                  if (manyItems == 0)
                  {
                  front = 0;
                  rear = 0;
                  }
                  else
                  rear = nextIndex(rear) ;

                  data[rear] = item;
                  manyItems++;
                  }


                  /**
                  * Determine whether this queue is empty.
                  * @param - none
                  * @return
                  * <CODE>true</CODE> if this queue is empty;
                  * <CODE>false</CODE> otherwise.
                  **/
                  public boolean isEmpty( )
                  {
                  return (manyItems == 0);
                  }


                  private int nextIndex(int i)
                  // Precondition: 0 <= i and i < data.length
                  // Postcondition: If i+1 is data.length,
                  // then the return value is zero; otherwise
                  // the return value is i+1.
                  {
                  if (++i == data.length)
                  return 0;
                  else
                  return i;
                  }


                  /**
                  * Accessor method to determine the number of items in this queue.
                  * @param - none
                  * @return
                  * the number of items in this queue
                  **/
                  public int size( )
                  {
                  return manyItems;
                  }


                  /**
                  * Reduce the current capacity of this queue to its actual size (i.e., the
                  * number of items it contains).
                  * @param - none
                  * <dt><b>Postcond ition:</b><dd>
                  * This queue's capacity has been changed to its current size.
                  * @exception OutOfMemoryErro r
                  * Indicates insufficient memory for altering the capacity.
                  **/
                  public void trimToSize( )
                  {
                  Object trimmedArray[ ];
                  int n1, n2;

                  if (data.length == manyItems)
                  // No change needed.
                  return;
                  else if (manyItems == 0)
                  // Just change the size of the array to 0 because the queue is empty.
                  data = new Object[0];
                  else if (front <= rear)
                  { // Create trimmed array and copy data[front]...data[rear] into it.
                  trimmedArray = new Object[manyItems];
                  System.arraycop y(data, front, trimmedArray, front, manyItems);
                  data = trimmedArray;
                  }
                  else
                  { // Create a trimmed array, but be careful about copying items into it. The queue items
                  // occur in two segments. The first segment goes from data[front] to the end of the
                  // array, and the second segment goes from data[0] to data[rear]. The variables n1
                  // and n2 will be set to the number of items in these two segments. We will copy
                  // these segments to trimmedArray[0...manyItems-1].
                  trimmedArray = new Object[manyItems];
                  n1 = data.length - front;
                  n2 = rear + 1;
                  System.arraycop y(data, front, trimmedArray, 0, n1);
                  System.arraycop y(data, 0, trimmedArray, n1, n2);
                  front = 0;
                  rear = manyItems-1;
                  data = trimmedArray;
                  }
                  }
                  public String toString(){
                  String s = "";
                  for(int i=0;i<data.leng th;i++){
                  s+=data[i]+" , ";
                  }
                  return "[ " + s + "]";
                  }
                  }



                  Note that I didn't write these classes I downloaded them from the enternet

                  Comment

                  • Laharl
                    Recognized Expert Contributor
                    • Sep 2007
                    • 849

                    #10
                    There are a few issues here:
                    1) Don't bold code, use the provided CODE tags instead.
                    2) This is clearly a homework assignment. If that code isn't part of your class, you're cheating. I hope my read is wrong...

                    Comment

                    • mia023
                      New Member
                      • May 2007
                      • 89

                      #11
                      Originally posted by Laharl
                      There are a few issues here:
                      1) Don't bold code, use the provided CODE tags instead.
                      2) This is clearly a homework assignment. If that code isn't part of your class, you're cheating. I hope my read is wrong...
                      It is an assignment type but this code(ObjectStac k-ObjectQueue) was said to be downloaded from the enternet. I told you at first that I don't need the answer I just need to understand why do we need to use ArrayList and why do we need the name of the stock.

                      Comment

                      • Laharl
                        Recognized Expert Contributor
                        • Sep 2007
                        • 849

                        #12
                        Ok. Sorry I misjudged you, our policies are quite strict on that subject, as are those of most professors. You don't necessarily need an ArrayList, you could use an array or a Vector or a LinkedList or anything else that can store a bunch of objects. As to why you need the identifier of the StockPurchase object, it's so you can add it to the collection you're using to store them.

                        Comment

                        Working...