I have created a generic class with few methods. I just want to call the method and add value but its not working. Here is the code
public interface GenericInterface<T> {
public T getValue();
public void setValue(T t);
}
public class FirstGeneric<T> implements GenericInterface<T> {
private T value;
public FirstGeneric(T _value) {
this.value = _value;
}
@Override
public T getValue() {
return value;
}
@Override
public void setValue(T t) {
this.value = t;
}
@SuppressWarnings("unchecked")
public static <T> T addValues(FirstGeneric<T> myGeneric, FirstGeneric<T> myGeneric1) {
T result = null;
if (myGeneric != null && myGeneric1 != null) {
T t1 = myGeneric.getValue();
T t2 = myGeneric1.getValue();
result = (T) t1.toString().concat(t2.toString());
System.out.println("Result is:=" + result);
}
return result;
}
public static void main(String args[]) {
Integer int1 = 1;
FirstGeneric<Integer> myInt = new FirstGeneric<Integer>(int1);
String value = "Hello";
FirstGeneric<String> myString = new FirstGeneric<String>(value);
addValues(myString, myInt);
}
}
But i am getting compilation error at last line.
The method addValues(FirstGeneric, FirstGeneric) in the type FirstGeneric is not applicable for the arguments (FirstGeneric, FirstGeneric)
What I am doing wrong? Thanks.
addValues
has a single generic type parameter, which means you can't pass to it both a FirstGeneric<Integer>
and a FirstGeneric<String>
.
To make the addValues(myString, myInt)
call valid, you can define two generic type parameters in your method:
public static <T,U> String addValues(FirstGeneric<T> myGeneric, FirstGeneric<U>
myGeneric1) {
String result = null;
if (myGeneric != null && myGeneric1 != null) {
T t1 = myGeneric.getValue();
U t2 = myGeneric1.getValue();
result = t1.toString().concat(t2.toString());
System.out.println("Result is:=" + result);
}
return result;
}
Note that I changed the return type to String
, since it's clearly a String
(produced by t1.toString().concat(t2.toString())
), so you can't cast it to T
and hope that T
would be a String
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments