7
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 ?

2

3 Answers 3

19

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.

0
6

The use of %s will result in the toString() method being called on the object, and thus will work for any type T.

1
  • Actually, if the object implements java.util.Formattable, then the object's formatTo method will be invoked. This way one can reserve toString for sebugging, and printf or format for human use. Oct 17, 2013 at 13:09
3

Take into accoun that almost everything can be turned into a String, be it by the toString() method or just by appending primitive values.

When %s is given, it will turn whatever element is into a String.

2
  • Primitive values aren't accepted for generics. You can still add them, say if T is instance of Integer, but all the ints you add will be boxed to an Integer.
    – user1181445
    Mar 2, 2013 at 19:41
  • 1
    @Legend That issue is a little tangential to this question though - it's about how Formatter works, not about how generics work. You can certainly printf primitives (although I believe they'll be boxed), and the question actually uses the boxed types anyway.
    – millimoose
    Mar 2, 2013 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.