使用泛型方法打印不同字符串的元素(泛型例子学习)

来源:互联网 发布:新天下无双挂机软件 编辑:程序博客网 时间:2024/06/14 02:37


使用泛型方法打印不同字符串的元素

package com.example.test;public class Test{    // 泛型方法 printArray    public < E > void printArray( E[] inputArray )    {        // 输出数组元素        for ( E element : inputArray ){            System.out.printf( "%s ", element );        }        System.out.println();    }    public static void main( String args[] )    {        Test c=new Test();                // 创建不同类型数组: Integer, Double  Character        Integer[] intArray = { 1, 2, 3, 4, 5 };        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };        System.out.println( "整型数组元素为:" );        c.printArray( intArray  ); // 传递一个整型数组        System.out.println( "\n双精度型数组元素为:" );        c.printArray( doubleArray ); // 传递一个双精度型数组        System.out.println( "\n字符型数组元素为:" );        c.printArray( charArray ); // 传递一个字符型数组    }}




不同类型的数据。


public class Box<T> {    private T t;    public void add(T t) {        this.t = t;    }    public T get() {        return t;    }    public static void main(String[] args) {        Box<Integer> integerBox = new Box<Integer>();        Box<String> stringBox = new Box<String>();              //  不同类型的数据        integerBox.add(new Integer(10));        stringBox.add(new String("菜鸟教程"));        System.out.printf("整型值为 :%d\n\n", integerBox.get());        System.out.printf("字符串为 :%s\n", stringBox.get());    }}

阅读全文
0 0