泛型
Java泛型本质是参数化类型,把类型作为参数传递。 常见形式有泛型类、泛型接口、泛型方法。 语法:<T, …> T称为类型占位符,表示一种引用类型。如果编写多个使用逗号隔开。 好处:
提高代码的重要性; 防止类型转换异常,提高代码的安全性。
参考代码(创建泛型)
public class MyGeneric < T> {
T t;
public void show ( T t) {
System. out. println ( t) ;
}
public T getT ( ) {
return t;
}
}
泛型类
注意
泛型只能使用引用类型; 不同泛型对象类型不能相互赋值。
参考代码(使用泛型创建对象测试)
public class TestGeneric {
public static void main ( String[ ] args) {
MyGeneric< String> myGeneric = new MyGeneric < String> ( ) ;
myGeneric. t = "hello" ;
myGeneric. show ( "泛型" ) ;
String string = myGeneric. getT ( ) ;
MyGeneric< Integer> myGeneric1 = new MyGeneric < > ( ) ;
myGeneric1. t = 123 ;
myGeneric1. show ( 666 ) ;
Integer integer = myGeneric1. getT ( ) ;
}
}
泛型接口
public interface MyInterface < T> {
String name = "王二" ;
T server ( T t) ;
}
public class MyInterfaceImpl1 implements MyInterface < String> {
@Override
public String server ( String s) {
System. out. println ( s) ;
return s;
}
}
public class MyInterfaceImpl2 < T> implements MyInterface < T> {
@Override
public T server ( T t) {
System. out. println ( t) ;
return t;
}
}
public class TestGeneric {
public static void main ( String[ ] args) {
MyInterfaceImpl1 impl1 = new MyInterfaceImpl1 ( ) ;
impl1. server ( "泛型接口" ) ;
MyInterfaceImpl2< Integer> impl2 = new MyInterfaceImpl2 < > ( ) ;
impl2. server ( 66 ) ;
}
}
泛型方法
public class MyGenericMethod {
public < T> T show ( T t) {
System. out. println ( "非静态泛型方法:" + t) ;
return t;
}
public static < W> W old ( W w) {
System. out. println ( "静态泛型方法:" + w) ;
return w;
}
}
package com. lb. demo2;
public class TestGeneric {
public static void main ( String[ ] args) {
MyGenericMethod myGenericMethod = new MyGenericMethod ( ) ;
myGenericMethod. show ( "非静态泛型方法" ) ;
myGenericMethod. show ( 6 ) ;
myGenericMethod. show ( 3.14 ) ;
MyGenericMethod. old ( "静态泛型方法" ) ;
MyGenericMethod. old ( 8 ) ;
MyGenericMethod. old ( 3.1415926 ) ;
}
}
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。 特点:
编译时即可检查,而非运行时抛出异常; 访问时,不必类型转换(拆箱); 不同泛型之间引用不能相互赋值,泛型不存在多态。
参考代码
import com. lb. demo1. Student;
import java. util. ArrayList;
import java. util. Iterator;
public class Demo03 {
public static void main ( String[ ] args) {
ArrayList< String> arrayList = new ArrayList < String> ( ) ;
arrayList. add ( "泛型集合" ) ;
for ( String string : arrayList) {
System. out. println ( string) ;
}
ArrayList< Student> arrayList1 = new ArrayList < Student> ( ) ;
Student s1 = new Student ( "小王" , 30 ) ;
Student s2 = new Student ( "小刘" , 21 ) ;
Student s3 = new Student ( "小帅" , 53 ) ;
arrayList1. add ( s1) ;
arrayList1. add ( s2) ;
arrayList1. add ( s3) ;
Iterator< Student> it = arrayList1. iterator ( ) ;
while ( it. hasNext ( ) ) {
Student s = it. next ( ) ;
System. out. println ( s. toString ( ) ) ;
}
}
}