Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html" rel="nofollow"><code>Stack</code></a> is a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html" rel="nofollow"><code>Collection</code></a> it implements <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#toArray%28T%5b%5d%29" rel="nofollow">the <code>toArray(T[])</code> method</a> so you could use that to convert your stack to an array and use your working array solution.</p> <p>However, you will have the problem that there is no autoboxing for arrays. Autoboxing automatically converts between primitive types and objects which means, for example, you can add <code>int</code> values directly to your <code>Stack</code> without creating <code>Integer</code> objects, as the compiler does this for you:</p> <pre><code>Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;(); stack.push(20); stack.push(53); </code></pre> <p>However, the compiler won't convert between <code>int[]</code> and <code>Integer[]</code> so you'd have to do:</p> <pre><code>Integer[] array = stack.toArray(new Integer[stack.size()]); </code></pre> <p>And using <code>Integer[]</code> would be a chore. </p> <p>So the easiest thing to do is this:</p> <pre><code>int[] array = new int[stack.size()]; for (int i = 0; i &lt; array.length; i++) { array[i] = stack.get(i); } </code></pre> <p>Creating an array once will be more efficient than repeatedly cloning and emptying a Stack.</p> <p>(Although if this is a homework question intended to teach you how to use stacks this might not be the best approach!)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload