I'm new to IntelliJ IDEA. I used to use Eclipse.
By default, IntelliJ doesn't ask to give parameter type for Java Generics Type.
// Following code doesn't give any warning
List list = null;
// I want to make IntelliJ ask me to specify type parameter (say Long)
List<Long> list = null; // i.e If I want a List of Long
How can I set up IntelliJ so that it ask me to give generic type parameters while using generics java types?
I'm using JDK 8 if it matters.
Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
IntelliJ provide an inspection name Raw use of parameterized class
After enabling that inspection.
In the Project Structure
menu, under Project
, check the language level setting. Setting it to 6.0
will cause the IDE to give you an error when you are missing the identifier in the diamond block.
Setting it to 7.0 or higher will suppress it.
Addition based on further exchange:
Under File -> Settings -> Inspections -> General
if the box that says Unchecked warning
is checked, when you run Analyze -> Inspect code
, it will report the condition noted under General -> Unchecked warnings
as "Unchecked call to add(E) as a member of raw type 'java.util.List'", in this example. If you declare the generic type of List explicitly, this warning will not show up in the report.
I am not aware of a way to get it to do exactly what you are asking for; however, once you would instantiate your List and then add an element to it IntelliJ will mark it with a yellow squiggly line and warn you it was unchecked. If you would put your cursor anywhere on the yellow squiggly and press Alt-Enter it will offer you "Try to generify YourClassName", press enter and it will infer the type and modify your code.
Before:
After:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With