can someone explain the generic return type of this method in java?

<R,C> specify generic type parameters and simply allow instances of visitor and context to work regardless of the object with which they were constructed.

So if

AstVisitor<Integer, String> = new AstVisitor(....);
String context = "....";

Then the method behaves as follows:

public Integer accept(AstVisitor<Integer, String> visitor, String context) {
       return ...; // returns an integer.

Note: The type parameters allow for the method to receive the arguments and specify a return type. However, the logic in the method must be appropriate for those types. Otherwise you will get either a compiler error or a runtime exception.

Here is a simple example.

public static void main(String[] args) {
    String result = foo("hello", 1);
    int result2 = foo(1, "hello");
public static <R,C> R foo(R r, C c) {
    return r; // just returns the argument



Since the number 1 above is an int and not an Integer, it converts it first to an Integer, then back to an int upon return. It does this because the method expects objects, not primitives. This is known as boxing and unboxing which, if you are unfamiliar, you should read about.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top