Есть класс MyGeneric<T> с полем a.
Нужно создать метод public T Add(T obj) который реализует сумму Integer и конкатенацию строк String. Как такое провернуть?
Например, вот так:
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;
}
}
Продвижение своими сайтами как стратегия роста и независимости