Search code examples
javaeclipsetype-erasurebidirectionalbimap

How to get around "Erasure of method is the same as another method" when writing a Bidirectional Map


Im currently trying to write a bidirectional map since (as far as I can see) Java doesnt provide one. My code is as follows.

private static final class ColourCharTwoWayMap<E,F> {

    private ArrayList<E> eArrayList;
    private ArrayList<F> fArrayList;

    private ColourCharTwoWayMap() {
        eArrayList = new ArrayList<E>();
        fArrayList = new ArrayList<F>();
    }

    public void put(E colour, F ch) {
        eArrayList.add(colour);
        fArrayList.add(ch);
    }

    public F get(E colour) throws ArrayIndexOutOfBoundsException {
        return fArrayList.get(eArrayList.indexOf(colour));
    }

    public E get(F ch) throws ArrayIndexOutOfBoundsException {
        return eArrayList.get(fArrayList.indexOf(ch));
    }
}

Eclipse is giving me the error "Erasure of method get(E) is the same as another method in type SaveManager.ColourCharTwoWayMap". From googling, I understand that Java doesn't like generic methods that do the same thing, and that its something to do with overriding and Java not knowing what method to use. It's all a little over my head.

What is a better way to do what I'm trying to do above? (ie have a method that takes an object of type E and returns an object of type F and vice versa).


Solution

  • Your two get functions have the same parameter type - a java.lang.Object due to the type erasure effect you have already alluded to. That's obviously not allowed since the function names are also the same and the compiler emits and error.

    The solution is simple, change the names to getE and getF