There is a class MyGeneric<T> with a field a . You need to create a method public T Add(T obj) that implements the sum of Integer and String concatenation. How to do this?

enter image description here

  • this.a += obj; ? - Flippy
  • public T Add (T obj) {return this.a + obj; } yes, corrected, but did not save. - Kryshtop

1 answer 1

For example, like this:

 private static class MyGeneric<T> { T value; @SuppressWarnings("unchecked") public T add(T value) { if (value instanceof String) return (T) concat(this.value.toString(), value.toString()); if (value instanceof Integer) return (T) sum((Integer) this.value, (Integer) value); return null; } private static Integer sum(Integer v1, Integer v2) { return v1 + v2; } private static String concat(String v1, String v2) { return v1 + v2; } }