Java – why use printf (‘% s’) to pass parameters to generic methods?

package genericMethods;
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 problem is that the method printarray () doesn't know what type of data to print out, and it seems that% d will have an error at runtime - but not just% s of string?

Solution

The problem is that you don't know what type of "element" will be In your example, it can be integer, double, or character In this case, you cannot use% d or% lf because they do not apply to types other than integer (for% d) or double (for% LF)

%S actually applies to all of these because all object types have Tostring(), so they can be converted into strings for printing

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>