how to use primitives with iterator

How do I use an iterator to get back a stack of ints? My code works with for a statement if i use Objects but not int. If i use a for statement with Objects it work. Does it have something to do with Integer autoboxing?

public class Simulator {

    public static void main(String[] args) {
        Stack<Integer> s = new Stack<Integer>(); 
        s.insert(15);
        s.insert(25);
        s.insert(7);

        for ( int t : s) {
            System.out.println(t);
        }
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stack;

import java.util.Iterator;

/**
 *
 * @author 
 */
public class Stack<Item> implements Iterable {

    /**
     * @param args the command line arguments
     */
    private Item[] arr;
    private int n; 

    public Stack() {
        System.out.println("Stack initialized");
        arr = (Item[]) new Object[1];
        n = 0;
    }

    public void insert(Item element) {
        if (n == arr.length) {
            resize(arr.length * 2);
        }
        arr[n++] = element;
    }

    @Override
    public Iterator iterator() {
        return new ListIterator(); 
    }

    private class ListIterator implements Iterator<Item> {

        private int i = n; 

        @Override
        public boolean hasNext() {
           return i > 0;
        }

        @Override
        public Item next() {
            return arr[--i];
        }

        @Override
        public void remove() {
        }
    }

    // resize the underlying array holding the elements
    private void resize(int capacity) {
        assert capacity >= n;
        Item[] temp = (Item[]) new Object[capacity];
        for (int i = 0; i < n; i++) {
            temp[i] = arr[i];
        }
        arr = temp;           
    }
}
Jon Skeet
people
quotationmark

The first problem is with your Stack class. It just implements the raw Iterable type. It should implement Iterable<Item> instead. Read more about raw types in the Java Generics FAQ.

You still wouldn't be able to create a Stack<int>, but the code using Stack<Integer> and iterating with an int iteration variable would be fine.

Once you've changed the class declaration to:

class Stack<Item> implements Iterable<Item>

and changed the iterator method to:

@Override
public Iterator<Item> iterator() {
    return new ListIterator();
}

... you'll still get lint warnings due to your array casts (which aren't actually checking anything) but the rest should be okay.

people

See more on this question at Stackoverflow