How can I perform an operation on operands of unknown types?
-
For example, let's take the operation +.
You need a function like this:
Object plus (Object left, Object right) {...}
What:
plus(1, 3); // = 4 (Integer) plus(1L, 3); // = 4 (Long) plus(1L, "test"); // = "1test" (String) plus(1, new Date()); // Exception
Java Adalyn Wallace, Sep 5, 2020 -
Something like this:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(plus(1, 3));
System.out.println(plus("one", 2));
}
public static Object plus(Object l, Object r){
Object ret=null;
if ((r instanceof Integer) && (l instanceof Integer)){
ret = (Integer)r+(Integer)l;
}
if ((r instanceof Integer) && (l instanceof String)){
ret =(String) r.toString()+l;
}
return ret;
}
}
4
2oneAnonymous
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!