"The method from ... is never used locally" on a public method inside an anonymous class

1.4k views Asked by At

I'm implementing the iterable interface and returning the iterator using anonymous class.

The problem is I can't use my custom add from the anonymous class in the main method.

I can't call the add method in the main method.
Eclipse complains that it's not defined.

What is the problem?
I'll spare from you the outer class and just show you the method iterator:

@Override
public Iterator<Symbol> iterator() {
    return new Iterator<Symbol>() {
        int i = 0; //Remove i and it works. WHY?!!

        public boolean hasNext() {
            return i < symArr.length && symArr[i] != null;
        }

        public Symbol next() {
            if (hasNext()) {
                return symArr[i++];
            }
            return null;
        }

        public void add(Symbol addMe) {
            if (i < symArr.length) {
                symArr[i] = addMe;
            }
        }
    };
}

My main method inside the outer class:

public static void main(String[] args) {
    SymbolTable st = new SymbolTable(22);
    Iterator<Symbol> it = st.iterator();
    it.next();
    it.add(new Symbol("2", 2)); //Have problem here. 
    //Problem disappears when I completely remove i variable in the iterator method.

}

The whole code:

package tirgul_iteratorsExceptions;

import java.util.Iterator;

public class SymbolTable implements Iterable<Symbol> {

    Symbol[] symArr;

    public SymbolTable(int size) {
        symArr = new Symbol[size];
    }

    public SymbolTable(SymbolTable st, boolean isDeep) {
        symArr = new Symbol[st.symArr.length];
        if (isDeep) {
            for (int i = 0; i < st.symArr.length; i++) {
                symArr[i] = new Symbol(st.symArr[i].name, st.symArr[i].value);
            }
        }
        // Shallow copy
        else {
            for (int i = 0; i < st.symArr.length; i++) {
                symArr[i] = st.symArr[i];
            }
        }
    }

    @Override
    public Iterator<Symbol> iterator() {
        return new Iterator<Symbol>() {
            int i = 0;

            public boolean hasNext() {
                return i < symArr.length && symArr[i] != null;
            }

            public Symbol next() {
                if (hasNext()) {
                    return symArr[i++];
                }
                return null;
            }

            public void add(Symbol addMe) {
                if (i < symArr.length) {
                    symArr[i] = addMe;
                }
            }
        };
    }

    public static void main(String[] args) {
        SymbolTable st = new SymbolTable(22);
        Iterator<Symbol> it = st.iterator();
        it.next();
        it.add(new Symbol("2", 2));

    }

}
0

There are 0 answers