0

I have a generic class:

public abstract class Container<T> {
  ...
  protected T value;
  private SomeType type;

  public T add(T toAdd);

  public Container(T value, SomeType type) {
     ...
  }
  ...
}

and a MathHelper-Class:

public class ContainerMathHelper {
   private ContainerMathHelper() {}
   
   public static Container<?> add(Container<?> a, Container<?> b) {
      check for same container-type as types are unique -> same impl of container
     
      ???

      return addT(casted_a, casted_b);
   }

   public static <T> Container<T> addT(Container<T> a, Container<T> b) {
      return a.add(b);
   }
}

now I don't know how to properly cast both a(Container<?>) and b(Container<?>) to the same type to use the addT function.

I already tried things like casting them both by using

clazzX.cast(a) and clazzX.cast(b) with clazzX being the same object

and some other things.

Does anybody know a solution?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
rababer30
  • 1
  • 1
  • You can't. See: https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens – Seelenvirtuose Jun 29 '22 at 09:55
  • 2
    You maybe should change the method's signature to ` Container add(Container a, Container b)` and let the compiler figure out whether the call to this method is allowed or not. – Seelenvirtuose Jun 29 '22 at 09:58
  • Seelenvirtuose is correct: The problem is the compiler doesn't know the wildcard is the *same* T for all usages. By typing the method, it locks the type to a *particular* type that is consistent for the whole method invocation. – Bohemian Jun 29 '22 at 10:02

0 Answers0