public static void input(int[] array){
}
public static void input(String[] array){
}
public static void input(double[] array){
}
As this is working fine I wanted to know is there any way to create a single function for all array data types. Can it apply to Array List?
CodePudding user response:
Yes, you can use generics for this purpose.
Having the function as static member
Implementation will looks like this,
public class ClassName { public static <T> void input(T[] array){ } }
And while using it Java will automatically interpret type
ClassName.input(new Integer[]{}); ClassName.input(new String[]{}); ClassName.input(new Double[]{});
Having the function as class member
Implementation will looks like this,
public class ClassName<T> { public void input(T[] array){ } }
And you can use it like using ArrayList
new ClassName<Integer>().input(new Integer[]{}); new ClassName<String>().input(new String[]{}); new ClassName<Double>().input(new Double[]{});
And Java generics won't support primitive types (int), only works with class types (Integer)
CodePudding user response:
If you want to avoid the boxing and unboxing of primitives, there isn't any GOOD way to make it shorter. You technically could try something along the lines of this with Java 19 and --enable-preview
:
public static void input(Object array) {
switch(array.getClass()) {
case int[] intArray -> {
for (int i : intArray) {
// do something useful
}
}
case double[] doubleArray -> {
// do something useful
}
case String[] stringArray -> {
// do something useful
}
default -> throw new IllegalArgumentException("Argument must be an array of type int[], String[], or double[].");
}
}
.. but then you are just manually doing what the Java language would do for you with the overloaded methods.