GenericWhitespace

Since Checkstyle 5.0

Description

Checks that the whitespace around the Generic tokens (angle brackets) "<" and ">" are correct to the typical convention. The convention is not configurable.

Left angle bracket ("<"):

  • should be preceded with whitespace only in generic methods definitions.
  • should not be preceded with whitespace when it is preceded method name or constructor.
  • should not be preceded with whitespace when following type name.
  • should not be followed with whitespace in all cases.

Right angle bracket (">"):

  • should not be preceded with whitespace in all cases.
  • should be followed with whitespace in almost all cases, except diamond operators and when preceding a method name, constructor, or record header.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="GenericWhitespace"/>
  </module>
</module>
        

Examples with correct spacing:

// Generic methods definitions
public void <K, V extends Number> boolean foo(K, V) {}
// Generic type definition
class name<T1, T2, ..., Tn> {}
// Generic type reference
OrderedPair<String, Box<Integer>> p;
// Generic preceded method name
boolean same = Util.<Integer, String>compare(p1, p2);
// Diamond operator
Pair<Integer, String> p1 = new Pair<>(1, "apple");
// Method reference
List<T> list = ImmutableList.Builder<T>::new;
// Method reference
sort(list, Comparable::<String>compareTo);
// Constructor call
MyClass obj = new <String>MyClass();
// Record header
record License<T>() {}
        

Examples with incorrect spacing:

List< String> l; // violation, "<" followed by whitespace
Box b = Box. <String>of("foo"); // violation, "<" preceded with whitespace
public<T> void foo() {} // violation, "<" not preceded with whitespace

List a = new ArrayList<> (); // violation, ">" followed by whitespace
Map<Integer, String>m; // violation, ">" not followed by whitespace
Pair<Integer, Integer > p; // violation, ">" preceded with whitespace

record License<T> () {} // violation, ">" followed by whitespace
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker