as far as I know I can't call the method like
concatenate<String>("One", "Two")
as that will give me an error
Actually, you can, only the syntax is a bit different:
public class Main {
public static <T> void concatenate(T arg1, T arg2) {
System.out.println(arg1.toString() + arg2.toString());
}
public static void main(String[] args) {
Main.<String>concatenate("one", "two"); // will work just fine, outputs "onetwo"
Main.<Integer>concatenate(1, 2); // will also work great, outputs 12
Main.<String>concatenate("one", 2); // will fail at compile time
}
}
If concatenate()
were a non-static
method, the syntax would be obj.<String>concatenate(...)
.
As to your second example:
public class Main {
public static <T> void quickSort(T... args) {
}
public static void main(String[] args) {
quickSort(5, "nine", 7, 3, "two", 5, 4, 1); // warning
Main.<Integer>quickSort(5, "nine", 7, 3, "two", 5, 4, 1); // error
}
}
Here, Main.<Integer>quickSort(...)
fails with the following error:
The parameterized method quickSort(Integer...) of type Main is not applicable for the arguments (Integer, String, Integer, Integer, String, Integer, Integer, Integer)