0

I am trying to convert my code into generic and I get an error at o1 + o2 stating that cannot find symbol for o1 and o2 then bad operand types for binary operator on the push(pop()+ pop()).

public abstract class MyStackGeneric <E> extends ArrayList <E>
{
    protected abstract E plus( E o1, E o2 );

    public void push (E i)
    {
        add (i);
    }

    public E pop () throws java.util.EmptyStackException
    {
        return remove (size()-1);
    }

    public void print(){
        ListIterator l = this.listIterator();

        while(l.hasNext())
        {
            System.out.print( l.next() + ", " );
        }

        System.out.println();
    }

    public E plus(E o)
    {
        return o1 + o2; //error here 
    }

    public void plus() throws ArithmeticException
    {
        if( size() < 2 ) throw new ArithmeticException("not enough element");
        push(pop()+ pop());//error here
    }
2
Contributors
1
Reply
18
Views
2 Years
Discussion Span
Last Post by JamesCherrill
0

The type E could be anything, String, URL, JButton... so there's no version of the + operator that can be used with all of those. What did you want it to do?

o1 and o2 are defined for the abstract 2-arg plus method, but not for the 1-arg version where you get the undefined symbols.

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.