《java入门第一季》之根据小案例体会泛型

时间:2023-03-09 07:53:31
《java入门第一季》之根据小案例体会泛型

泛型在哪些地方使用呢?

* 看API,如果类,接口,抽象类后面跟的有<E>就说要使用泛型。一般来说就是在集合中使用。

下面根据案例,加深体会泛型的作用。

案例一:

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"); 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);
}
}
}

案例二:

使用泛型存储学生对象。

一、建立学生类

/**
* 这是学生描述类
*
* @author 杨道龙
* @version V1.0
*/
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;
} }

二、泛型使用。

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());
}
}
}