0

I have got this situation:

public abstract class Parent {
    public Parent(){}
}

public class Child extends Parent{
    public Child(){
    }
}

public class Main {
    public static void main(String[] args) {
        HashMap<Child, Double> mapChild = new HashMap<>();
        HashMap<Parent, Double> mapParent = new HashMap<>();

        foo(mapChild, new Child()); //Wrong 1 arg type
        foo(mapParent, new Child());
    }

    public static void foo(HashMap<Parent, Double> x, Parent parent){
        x.put(parent, 5.0);
    }
}

This code does not work, because foo(mapChild, new Child()) said - "Wrong argument type".
I tried somethig with Wildcards, but i think it cant work with it. I can create second foo method, but i do not want to duplicate code.

Any ideas?

B_Osipiuk
  • 888
  • 7
  • 16

2 Answers2

1

Use

<? extends Parent>

in your collection. So the collection can accept both Child and Parent.

Xavier Bouclet
  • 922
  • 2
  • 10
  • 23
  • That is actually the wrong approach. It would be better to make the method `foo(...)` generic in the second parameter (`parent`) and set the `Map` to ` super T>` (where `T` is the type of the second argument). – Turing85 Nov 01 '17 at 20:58
  • He said any idea. It was mine. Just so you know your comment would have been much better without the first sentence. We are all here sharing ideas. With different level and skills. I didn’t think about the accepted solution. I am glad other did. – Xavier Bouclet Nov 02 '17 at 20:28
1

I believe what you want is

public static <T> void foo(Map<T, Double> x, T t) {
  x.put(t, 5.0);
}

...not to actually put a Parent object in a Map<Child, Double>.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413