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

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

Fortunately, I found the correct syntax for the return type static <T>Matcher not(Matcher<T> m)... although I don't understand why

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

Why is this a <T>Matcher in the return type? What is the concept of this?

I come from C ++ and handle its templates well. I know that Generics work differently, but why it scares me.

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

 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 ... */ } 
+8
java generics return-type hamcrest
source share
2 answers

Do you really want

 static <T> Matcher<T> 

You need to first “T” to declare the type for the general method. The second "T" is a type parameter for the Matcher class.

+9
source share

Towi Hope this illustration helps.

enter image description here

The above illustration is a direct answer to the title of the question: why is it <T>Type as a return type in Java Generics, and not Type<T> ?

There are a few additional points that should be considered in the Towi example, see comment trace.

+11
source share

All Articles