LinieKiste
LinieKiste

Reputation: 45

What does a generic in front of a method mean?

I found a function that basically looks like this:

<R> MyClass<R> functionName(){}

I have no Idea what the <R> right in front means and I didn't really find anything by googling it. I know what generics are, I just dont know what they do in that specific spot.

Upvotes: 1

Views: 805

Answers (3)

WJS
WJS

Reputation: 40044

It will let you write methods that can act as general purpose helper methods for any type.

Here is an example of reversing the contents of a List implementation and return it in an ArrayList.

        List<String> liststr = new ArrayList<>(List.of("A","B","C"));
        List<String> reversed = reverse(liststr);
        System.out.println(reversed);

        List<Integer> listint = new ArrayList<>(List.of(1,2,3,4));
        List<Integer> reverseint = reverse(listint);
        System.out.println(reverseint);

And here is the method.


    public static <T>  List<T> reverse(ArrayList<T> list) {
        List<T> rev = new ArrayList<>();
        for (int i = list.size()-1; i >= 0; i--) {
            rev.add(list.get(i));
        }
        return rev;
    }

This could have been done a different way but it would require casting of the return value and might also generate a runtime cast exception.

As in all generic methods and classes, type conflicts will be resolved at compile time and not at runtime.

Upvotes: 3

Imani
Imani

Reputation: 36

The first is a kind of declaring that functionName will use generics, generally we use R to represent "return", which means this function will return an instance of MyClass which manipulates R objects.

For better understanding, this is a way to call functionName if it was static:

public class AClass{

   class MyClass<TYPE>{}

   static <R> MyClass<R> functionName(){return null;}

   public static void main(String[] args) {
      AClass.<String>functionName();
   }

}

Upvotes: 2

Maxdola
Maxdola

Reputation: 1650

This means that the R is a variable, which is assigned when the method is executed and can be assigned any class. This might help: What are Generics in Java?

Upvotes: 1

Related Questions