1

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).

Ewan Brown
  • 143
  • 1
  • 9

3 Answers3

1

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

A better way would be to give your two getters different names.

djkhen
  • 1
  • 2
0

If either of the two values is supposed to have a particular parent class, IE looks like Color and Char are you values, you can get around the type erasure, but allow for sub classing of Color and Char, by saying that E extends Color or F extends Char. This makes them more "concrete" and the compiler able to differentiate between the two. However, if your Color or Char are derived from the same parent class, IE object or String, you would need to implement different method signatures.

IE public F getChByColour(E colour) and public E getColourByChar(F char)

JDL
  • 1,477
  • 21
  • 31