package genericMethods;
public class OverloadedMethods {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] integerArray = {1, 2, 3, 4, 5};
Double[] doubleArray = {1.0, 2.0, 3.0, 4.0, 5.0};
Character[] charArray = {'a', 'b', 'c', 'd'};
System.out.println("A has: ");
printArray(integerArray);
System.out.println("B has: ");
printArray(doubleArray);
System.out.println("C has: ");
printArray(charArray);
}
public static <T> void printArray(T[] array)
{
for(T element : array)
System.out.printf("%s ", element);//why use %s instead of others?
System.out.println();
}
}
My question is the method printArray() doesn't know what type of data is going to print out, and seems %d will occur error at run time - but isn't %s for String only ?
%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.
The issue is that you don't KNOW what type "element" will be. In your example, it could be Integer, Double, or Character. That being the case, you can't use %d or %lf, because those wouldn't work for types that aren't Integer (for %d) or Double (for %lf).
%s actually works for them all, because all Object types have a .toString(), so they can all be converted to Strings for printing.
The use of %s
will result in the toString()
method being called on the object, and thus will work for any type T
.
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