Java基础之泛型
泛型提供了编译时类型安全监测机制,该机制允许程序员在编译时检测到非法的类型。
泛型方法
public class FxDemo {
public static <E> void print(E arr[]){
for(E data: arr){
System.out.println(data);
}
}
public static void main(String[] args) {
Integer []a = {1,2,3};
Double []b = {4.0,5.0,6.0};
String []c = {"7","8","9"};
FxDemo.print(a);
FxDemo.print(b);
FxDemo.print(c);
}
}
有界类型的参数
限制那些被允许传递到一个类型参数的类型种类范围。
要声明一个有界的类型参数,首先列出类型参数的名称,后跟extends关键字。
public static <T extends Comparable<T>> T compare(T x,T y,T z){
T max = x;
if(y.compareTo(max)>0){
max = y;
}
if(z.compareTo(max)>0){
max = z;
}
return max;
}
泛型类
package classs.fx;
public class FxDemo<T> {
public static <E> void print(E arr[]){
for(E data: arr){
System.out.println(data);
}
}
public T say(T str){
return str;
}
public static <T extends Comparable<T>> T compare(T x,T y,T z){
T max = x;
if(y.compareTo(max)>0){
max = y;
}
if(z.compareTo(max)>0){
max = z;
}
return max;
}
public static void main(String[] args) {
FxDemo<String> fxDemo = new FxDemo<>();
Integer []a = {1,2,3};
Double []b = {4.0,5.0,6.0};
String []c = {"7","8","9"};
FxDemo.print(a);
FxDemo.print(b);
FxDemo.print(c);
System.out.println("==============");
System.out.println(FxDemo.compare(5,3,7));
System.out.println("==============");
System.out.println(fxDemo.say("haha"));
}
}
类型通配符
类型通配符一般是使用?代替具体的类型参数,例如list<?>在逻辑上代表list,list
public static <T extends Comparable<T>> T compare(T x,T y,T z){
T max = x;
if(y.compareTo(max)>0){
max = y;
}
if(z.compareTo(max)>0){
max = z;
}
return max;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
}