为什么将printf(“%s”)用于传递给泛型方法的参数? [英] Why use printf("%s") for arguments passed to generic methods?

查看:155
本文介绍了为什么将printf(“%s”)用于传递给泛型方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }

}

我的问题是方法printArray( )不知道打印出什么类型的数据,并且似乎%d将在运行时发生错误 - 但不仅仅是String的%s?

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 ?

推荐答案

问题在于你不知道元素的类型。在您的示例中,它可以是Integer,Double或Character。在这种情况下,您不能使用%d或%lf,因为这些不适用于非Integer(对于%d)或Double(对于%lf)的类型。

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实际上适用于所有人,因为所有对象类型都有.toString(),所以它们都可以转换为字符串进行打印。

%s actually works for them all, because all Object types have a .toString(), so they can all be converted to Strings for printing.

这篇关于为什么将printf(“%s”)用于传递给泛型方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆