泛型集合

ArrrayList存储并遍历字符串:
在集合中存储了String类型和Integer类型
编译时没问题,但是遍历时(运行时),我们把Integer当成String来执行,做了一个转换,就会报错
数组 例子:
String [] arr=new String[3];
arr[0] = “hello”;
arr[1]= “ok”;
arr[2]=1;//报错
集合也是模仿数组做着同样的处理,在创建对象的时候就明确了要存储的类型,但是在最后得遍历时,迭代器发现了不一样的类型,就报错

针对这个一个危险的问题,java提供了一种技术,在定义集合的额时候就能限制能够存储的数据类型

泛型:是一种把类型明确的工作推迟到了创建对象或调用对象的时候明确

格式:
<数据类型>
此处的数据类型只是引用类型

好处:
1.把运行时间的问题提到编译期
2.便面了强制转化的问题
3.优化了程序的设计,解决了黄色警告线
例子1:

 public class ArrayListdemo1 {
    	public static void main(String[] args) {
    		//创建集合
    		ArrayList list =new ArrayList();
    		list.add("hello");
    		list.add("world");
    		list.add("还行");
    	/*	list.add(12);
    		list.add(new Integer(100));//java.lang.ClassCastException*/
    //		Integer不能转换成String类型
    //		相当于list.add(Integer.valueOf());
    		
    		Iterator it=list.iterator();
    		while(it.hasNext()) {
    			String s=(String)it.next();
    			System.out.println(s);
    		}
    	}
    }

泛型的应用:
一般类、集合、抽象类都可以限制泛型
一般只用在集合;
例子1:

public class ArrayListdemo2 {
	public static void main(String[] args) {
		//创建泛型集合
		ArrayList<String> array=new ArrayList<String>();
		array.add("hello");
		array.add("ok");
//		array.add(12);//报错,限制了添加String
		Iterator<String> it=array.iterator();
		while(it.hasNext()) {
			String s=it.next();//已经限制了String类型,则不需要强转
			System.out.println(s);
		}
	}
}

例子2:

public class ArrayListdemo3 {
	public static void main(String[] args) {
		//创建对象
		//JDK的新特性:泛型推断 不建议使用//ArrayList<Student> array=new ArrayList<>();
		ArrayList<Student> array=new ArrayList<Student>();
		
		//创建元素对象
		Student s1=new Student(18,"小样");
		Student s2=new Student(13,"小小");
		Student s3=new Student(18,"不咋地");
		Student s4=new Student(18,"周杰伦");
		
		array.add(s1);
		array.add(s2);
		array.add(s3);
		array.add(s4);
		
		//遍历
		Iterator<Student> it=array.iterator();
		while(it.hasNext()) {
			Student s=it.next();
			System.out.println(s.getAge()+"------"+s.getName());
		}
		System.out.println("-------1---------");
		for(int i=0;i<array.size();i++) {
			Student s=array.get(i);
			System.out.println(s.getAge()+"------"+s.getName());
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值