泛型
为什么要使用泛型
我们需要在数组中对各种类型(如整形数组,字符串数组等其他类型数组)的数组进行排序,但是传统的数组只能对单一类型的数组进行排序。所以,我们可以用泛型的方法来对整型,浮点数,字符串等类型数组进行排序.。
泛型分为泛型方法和泛型类
使用方法
-
声明泛型参数,在方法返回类型的前面, 在类名的后面,用<>表示,在<>里写一个通配符,里面可以写任何单词,字母。常用E表示元素。
-
在泛型里声明要注意类型参数只能使用引用型类型。如(int要使用integer,char要使用string)
byte->Byte short->Short int->Integer long->Long
float->Float double->Double char->Character boolean->Boolean
泛型方法
public class Test
{
// 泛型方法
Object [] e;// 存储结构 : Object[] 是所有数据类型的父类
public static < E > void get( Object[] e )
{
// 输出数组元素
for (int i = 0 ;i<5;i++){
System.out.println(e [i].toString());
}
System.out.println();
}
public static void main( String args[] )
{
// 创建不同类型数组: Integer, Double 和 String
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 ,5.5};
String[] stringArray = {"he","llo","hello","hell","helo"};
System.out.println( "整型数组元素为:");
get(intArray);
// 整数型数组
System.out.println( "\n双精度型数组元素为:");
get(doubleArray);
// 双精度型数组
System.out.println( "\n字符型数组元素为:");
get(stringArray);
// 字符串数组
}
}
输出样式:
泛型类
public class List<E> {
E e;
public void add(E e) {
this.e = e;
}
public E print() {
return e;
}
public static void main(String[] args) {
List<Integer> integerList = new List<Integer>();
List<String> stringList = new List<String>();
integerList.add(10);
stringList.add("hello");
System.out.println("整型值为 :");
System.out.println(integerList.print());
System.out.println("字符串为 :");
System.out.println(stringList.print());
}
}
输出样式: