泛型诞生的作用:
1.增加编译期间的类型检查:泛型是作用再编译期的一种机制,即运行期间没有泛型的概念
2.取消类型转换的使用
泛型分类:
(1)泛型类:
public class MyArrayList<E> {
private E<> array;
private int size;
(2)泛型方法
MyArrayList<Book> books = new MyArrayList<Book>();
books.add(new Book());
在上面代码中我们可以得知,泛型类的使用方式:只需要在所有类型后边跟尖括号,并且尖括号内是真正的类型,即 E 可以看作是最后的类型
泛型总结:
泛型在运行期间,将所有的都擦除为object类;可以自动检查和转换;
泛型是为了解决某些容器、算法等代码的通用性而引入,并且能在编译期间做类型检查。
泛型利用的是 Object 是所有类的祖先类,并且父类的引用可以指向子类对象的特定而工作。
泛型是一种编译期间的机制,
泛型是 java 中的一种合法语法,标志就是尖括号 <>
包装类的基本语法:
基础数据类型和包装类的关系:
基本上就是类型的首字母大写,除了 Integer 和 Character
举例:
基本数据类型为 :int,包装类为 :Integer
基本数据类型为 :char,包装类为 :Character
基本数据类型为 :short,包装类为 :Short
基本数据类型为 :long ,包装类为 :Long
基本数据类型为 : byte ,包装类为 : Byte
基本数据类型为 : boolean ,包装类为 : Boolean,
包装类的使用:
(1) 装箱和拆箱:
//包装类的装箱
//新建一个 Integer 对象,将 i 的值放入对象的某个属性中
int i = 10;
Integer ii = Integer.valueOf(i);
Integer ij = new Integer(i);
System.out.println("ii = " + ii);
System.out.println("ij = " + ij);
//包装类的拆箱
//将 Integer 对象中的值取出,放到一个基本数据类型中
Integer jk = Integer.valueOf(20);
int j = jk.intValue();
System.out.println("j = " + j);
(2) 自动装箱和自动拆箱
//自动装箱
int a = 100;
Integer aa = a;
Integer ab = (Integer)a;
System.out.println("aa = " + aa);
System.out.println("ab = " + ab);
//自动拆箱
int c = aa;
int d = (int)aa;
System.out.println("c = " + c);
System.out.println("d = " + d);
注意:
自动装箱和自动拆箱是工作在编译期间的一种机制