泛型概述:JDK5的新特性——泛型
1、泛型技术的引入
(1)问题:
ArrayList存储字符串并遍历,我们按照正常的写法来写这个程序, 结果确出错了。为什么呢?
因为我们开始存储的时候,存储了String和Integer两种类型的数据。而在遍历的时候,我们把它们都当作String类型处理的,做了转换,所以就报错了。但是呢,它在编译期间却没有告诉我们。所以,我就觉得这个设计的不好。
回想一下,我们的数组
String[] strArray = new String[3];
strArray[0] = "hello";
strArray[1] = "world";
strArray[2] = 10; //直接在编译期间就报错提示我们
集合也模仿着数组的这种做法,在创建对象的时候明确元素的数据类型。这样就不会在有问题了。而这种技术被称为:泛型。
(2)泛型:
泛型是一种把类型明确的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型。
也叫做 参数化类型,把类型当作参数一样的传递。
(3)格式:
<数据类型> 注意:此处的数据类型只能是引用类型。
(八大引用类型:Short、Integer、Long、Character、Boolean、Float、Double、Byte)+String
(还包括一些自定义类型Student等)
(4)使用泛型的好处:
A: 把运行时期的问题提前到了编译期间。
B: 避免了强制类型转换。
C: 优化了程序设计,解决了黄色警告线。
2、泛型技术的使用演示1:存储字符串
(1)泛型在哪些地方使用呢?
看API,如果类、接口、抽象类后面跟的有<E>,就说明要使用泛型。一般来说就是在集合中使用。
(2)使用ArrayList存储字符串类型
(List:ArrayList、Vector、LinkedList)
package cn.itcast_02;
import java.util.ArrayList;
import java.util.Iterator;
/*
* 泛型在哪些地方使用呢?
* 看API,如果类,接口,抽象类后面跟的有<E>就说要使用泛型。一般来说就是在集合中使用。
*/
public class ArrayListDemo {
public static void main(String[] args) {
// 用ArrayList存储字符串元素,并遍历。用泛型改进代码
ArrayList<String> array = new ArrayList<String>();
array.add("hello");
array.add("world");
array.add("java");
array.add("javaEE");
Iterator<String> it = array.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
System.out.println("-----------------");
for (int x = 0; x < array.size(); x++) {
String s = array.get(x);
System.out.println(s);
}
}
}
3、泛型技术的使用演示2:存储自定义对象
package cn.itcast_02;
import java.util.ArrayList;
import java.util.Iterator;
/*
* 需求:存储自定义对象并遍历。
*
* A:创建学生类
* B:创建集合对象
* C:创建元素对象
* D:把元素添加到集合
* E:遍历集合
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// 创建集合对象
// JDK7的新特性:泛型推断。
// ArrayList<Student> array = new ArrayList<>(); //但是我不建议这样使用。
ArrayList<Student> array = new ArrayList<Student>();
// 创建元素对象
Student s1 = new Student("曹操", 40);
Student s2 = new Student("蒋干", 30);
Student s3 = new Student("诸葛亮", 26);
// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
// 遍历
Iterator<Student> it = array.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.getName() + "---" + s.getAge());
}
System.out.println("------------------");
for (int x = 0; x < array.size(); x++) {
Student s = array.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
*************************************************
package cn.itcast_02;
public class Student {
// 姓名
private String name;
// 年龄
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
---------------------
作者:stormchenmeng
来源:CSDN
原文:https://blog.csdn.net/cmm0401/article/details/80046082
版权声明:本文为博主原创文章,转载请附上博文链接!