Java-泛型

本文详细介绍了Java中的泛型,包括泛型类、泛型接口、泛型方法及其带来的好处。通过示例展示了如何使用泛型创建安全的集合,避免类型转换异常,提高代码的重用性和安全性。此外,还探讨了泛型在接口实现和方法定义中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型

  是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
  常见形式有泛型类,泛型接口,泛型方法
  语法:
    <T,…>T称为类型占位符,表示一种引用类型。
  好处:
    1)提高代码的重用性;
    2)防止类型转换异常,提高代码的安全性。

泛型类

/**
* 泛型类
* 语法:类命<T>
* T是类型占位符,表示一种引用类型,如果写多个使用逗号隔开
*/
public class MyGeneric<T>{
	//使用泛型T
	//1 创建变量
	T t;
	//2 作为方法的参数
	public void show(T t){
		System.out.println(t);
	}
	//泛型作为方法的返回值
	public T getT(){
		return t;
	}
}

public class TestGeneric{
	public static void main(String[] args){
		//使用泛型创建对象
		//注意:1 泛型只能使用引用类型 2 不同泛型对象不能相互复制
		MyGeneric<String> myGeneric=new MyGeneric<String>();
		myGeneric.t="world";
		mtGeneric.show("大家好");
		String string=myGeneric.getT();
		
		MyGeneric<Integer> myGeneric2=new MyGeneric<Integer>();
		myGeneric2.t=100;
		mtGeneric2.show(510);
		String string=myGeneric2.getT();
	}
}

泛型接口

/**
*注意:不能泛型静态常量
* 
*/
public interface MyInterface<T>{
	String name="张三";
	T server(T t);
}
//1. 确定类型
public class MyInterfaceImpl implements MyInterface<String>{
	@override
	public String server(Sting t){
		// TODO Auto-generated method stub
		System.out.println(t);
		return null;
	}
}
//2. 不确定类型
public class MyInterfaceImpl2<T> implements MyInterface<T>{
	@override
	public String server(Sting t){
		System.out.println(t);
		return null;
	}
}

public class TestInterface{
	MyInterfaceImpl impl=new MyInterfaceImpl();
	impl.server("xxxxx");

	MyInterfaceImpl2<Interger> impl2=new MyInterfaceImpl2<>();
	impl.server(1000);
}

泛型方法

/**
* 语法:<T> 返回值类型
*/
public class MyGenericMethod{
	//泛型方法
	public <T> T show(T t){
		System.out.println("泛型方法"+t);
		return t;
	}
}

public class TestInterface{

	MyInterfaceImpl2<Interger> impl2=new MyInterfaceImpl2<>();
	impl.server(1000);
	
	MyGenericMethod myGenericMethod=new MyGenericMethod();
	myGenericMethod.show("abcd");
}

泛型好处

  1)提高代码的重用性;(不用泛型,会使用方法重载)
  2)防止类型转换异常,提高代码的安全性。

泛型集合

   概念:参数化类型,类型安全的集合,强制集合元素的类型必须一致。
   特点:
    编译时即可检查,而非运行时抛出异常;
     访问时,

public class Demo2{
	public static void main(String args){
		ArrayList<String> arrayList=new ArrayList<String>();
		arrayList.add('xxx');
		arrayList.add('xxx');
		arrayList.add(123);//此时泛型为String,添加Integer会报错
		arrayList.add(345);//
		for(Object obj:arrayList){
			String s=(String) obj;//若不适用泛型,则会出现强制错误
			System.out.println(s);
		}
		
		ArrayList<Student> arrayList=new ArrayList<Student>();
		Student s1=new Student("曹",14);
		Student s2=new Student("曹",14);
		arrayList.add(s1);
		arrayList.add(s1);
		for(Student stu:arrayList){
			System.out.println(stu.toString());
		}
		Iterator<Student> it=arrayList.iterator();
		while(it.hasNext()){
			Student s=it.next();
			System.out.println(s.toString());
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值