Java泛型
package generic;
import java.util.ArrayList;
public class BackGround {
public static void main(String[] args) {
//对象函数的调用需要在 main 方法中进行相关的调用 这里更多的是考虑到 static 静态修饰符的影响
//泛型更多的是在集合当中的使用
ArrayList list =new ArrayList();
list.add("java ");
list.add(100);
list.add(true);
//利用简易的for循环进行遍历
// for(int i:list){ 自动报错 这里需要的是一个 object的对象 而不是简单的整形
//
// }
//
for(Object o:list){
System.out.println(o); //通过集合自动的添加的数据视为对象 即 add添加的对象都是按照object进行接受的
// String str=(String ) o;
// System.out.println(str);
}
ArrayList strList =new ArrayList<>();
//泛型的方式就会提供一种在编译的时候做检查的机制
strList.add("java");
strList.add("python");
strList.add("c++");
for(String o:strList){ //这个时候就以String类型进行数据的接收 因为我们在之前就已经 规定了接收的类型
System.out.println(o);
}
ArrayList arr=new ArrayList<>();
arr.add(100); //这里我们填充了一个 int 类型的数据 100 这时候会进行一个自动装箱的过程
for (int o:arr){
System.out.println(o); //这个时候又会进行一个自动拆箱的过程
}
//泛型类在创建对象的时候去指定具体的对象类型 在创建类的时候我们并不知道 这给对象到底是什么类型的
Generic strGeneric =new Generic<>("abc"); //第二个尖括号不写称为零形语法
System.out.println(strGeneric.getKey());
Generic integerGeneric=new Generic<>(100);
System.out.println(integerGeneric.getKey());
//我们声明了一个泛型类就可以操作多种数据类型
//当泛型类在创建对象的时候 如果没有指定数据类型 ,那么默认就视为对象进行操作
Generic str1=new Generic(2);
Generic str2=new Generic(true); //这样就会视为对象进行操作
//泛型类不支持基本的数据类型
// Generic =new Generic<>(100); 是不支持的
System.out.println(integerGeneric.getClass()==strGeneric.getClass()); //true 同一泛型类创建的时候指定不同的数据类型
//其指向的还是同一个类型 逻辑上不同 但实际相同
}
}
class Generic {
//T是由外部传入的数据类型决定的
//定义范型变量
private T key;
//构造方法
public Generic(T key) {
this.key = key;
}
//成员方法
public T getKey() {
return key;
}
public void setKey(T key) {
this.key = key;
}
@Override //toString方法的重载
public String toString() {
return "Generic{" +
"key=" + key +
'}';
}
}



