JAVA学习笔记37——泛型3:泛型嵌套+泛型数组+1.7新特性

最近在看JAVA教学的视频,觉得老师讲的很好,同时借用源代码还有笔记来撰写本系列博客,记录自己的学习内容,同时也供看到的人学习。

本篇将剩下的三点介绍完。

NO.4:泛型的嵌套:


示例代码:

public class Bjsxt <T>{
 T stu ;
 public static void main(String[] args) {
	 //泛型的嵌套 
	 Bjsxt<Student<String>> room =new  Bjsxt<Student<String>>();
	 //从外到内一层一层拆分
	 room.stu = new Student<String>();
	 Student<String> stu = room.stu;
	 String score =stu.score;
	 System.out.println(score);
}
}
NO.5:泛型数组:


虽然理论上来说没有泛型数组,但是向实现多态的功能一样,我们可以用Object类型的数组作为“障眼法”,在需要的时候通过强制转换类型转为我们所需要的类型:

/**
 * 没有泛型数组
 * 声明可以使用,但是创建失败,所以整体上是不行的
 */
public class Array {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Integer[]  arr = new Integer[4]; 
		//Student<String>[] arr2 = new Student<String>[10];  //这样就不行了
		Student<?>[] arr2 = new Student[10];  //创建的部分没有泛型即可,后期想添加自己制定的类型直接强制类型转换即可
		MyArrayList<String> strList =new MyArrayList<String>();
		strList.add(0, "a");
		String elem =strList.getElem(0);
		System.out.println(elem);
	}
}
class MyArrayList<E>{
	//E[] cap =new E[10]; 没有泛型数组
	Object[] cap = new Object[10];   //Object可以接收任意类型
	public void add(int idx,E e){
		cap[idx] =e;
	}
	@SuppressWarnings("unchecked")
	public E[] getAll(){
		return (E[]) cap;  //强制类型转换,即可正常使用
	}
	@SuppressWarnings("unchecked")
	public E getElem(int idx){
		return (E) cap[idx];
	}
}
NO.7:JDK1.7下泛型新特性:


示例代码:

import java.util.ArrayList;
import java.util.List;
/**
 * 1.7中使用泛型,声明一次类型即可
 * 在使用|创建时不用指定类型
 */
public class Test7 {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<String>  arrList= new ArrayList<String>();
		//List<String>  arrList2= new ArrayList<>();   JDK1.7里面这样写即可
	}
}
好了,关于泛型的知识就介绍完毕了,其实这里博主自己看视频的时候学的稀里糊涂的,回头还的多看几遍,琢磨琢磨,嘿嘿~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值