Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it `<T>Type` as return type in Java Generics and not `Type<T>`?

I just wrote a simple JUnit Matcher for assertThat() which requires Generics, of course.

By a bit of luck I found the right syntax for the return type of static <T>Matcher not(Matcher<T> m)..., although I don't understand why

  • in the return type its <T>Matcher and
  • in the argument list its Matcher<T>

Why is it <T>Matcher in the return type? What is the concept behind this?

I am coming from C++ and can handle its Templates there quite well. I know that Generics work differently, but that's why this is confusing to me.

Here is my own Matcher class. Look at the static helper not:

import org.hamcrest.*;

/** assertThat(result, not(hasItem("Something"))); */
class NotMatcher<T> extends BaseMatcher<T> {
    /** construction helper factory */
    static <T>Matcher not(Matcher<T> m) {  //< '<T>Matcher' ???
        return new NotMatcher<T>(m);
    }
    /** constructor */
    NotMatcher(Matcher<T> m) { /* ... */  }
    /* ... more methods ... */
}
like image 717
towi Avatar asked May 07 '13 15:05

towi


People also ask

Why do we use T in generics?

In other words, the T is an actual part of the syntax for Generics and it means that the paramter for the Class can be of variable type? <T> is the generic type. Maybe read the official tutorial. Yes, the angle-brackets with one (or more) types is the syntax for generics.

What does T stand for in Java generics?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

What is the difference between T and E in Java generics?

6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ).

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.


1 Answers

Towi I hope this illustration helps.

enter image description here

The above illustration is a direct response to the question's title: Why is it <T>Type as return type in Java Generics and not Type<T>?

There are several more additional points to consider in Towi's example, see comment trail.

like image 128
Jops Avatar answered Sep 22 '22 01:09

Jops