java-泛型规范写法-案例:
package com.etc.fanxing2;
public class GenericList<T> {
// 通用节点类型
private static class GenericNode<T> {
T value;
GenericNode<T> next;
}
// 固定头节点
private GenericNode<T> head = new GenericNode<T>();
public GenericList() {
}
// 添加一个对象
public void add(T value) {
// 找到末节点
GenericNode<T> tail = head;
while (tail.next != null)
tail = tail.next;
// 附加到末尾
GenericNode<T> node = new GenericNode<T>();
node.value = value;
tail.next = node;
}
// 长度
public int length() {
int count = 0;
GenericNode<T> m = head.next;
while (m != null) {
count += 1;
m = m.next;
}
return count;
}
// 获取迭代器
public Iterator<T> getIterator() {
Iterator<T> iter = new Iterator<T>();
iter.node = this.head;
return iter;
}
//老师//
public static class Iterator<T> {
private GenericNode<T> node;
// 是否还有下一节点
public boolean hasNext() {
return node.next != null;
}
// 获取下一节点的值
public T next() {
T value = node.next.value;
node = node.next;
return value;
}
}
}
package com.etc.fanxing2;
public class Student {
public int id;
public String name;
public String phone;
public Student() {
}
public Student(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return String.format("学生(%d, %s, %s)", id, name, phone);
}
}
package com.etc.fanxing2;
public class Teacher {
public String name; // 老师名字
public String major; // 主教课程
public Teacher() {
}
public Teacher(String name, String major) {
this.name = name;
this.major = major;
}
@Override
public String toString() {
return String.format("老师(%s, %s)", name, major);
}
}
package com.etc.fanxing2;
public class Test {
public static void main(String[] args) {
GenericList<Student> list = new GenericList<Student>();
list.add(new Student(1, "shao", "13810012345"));
list.add(new Student(2, "wang", "15290908889"));
list.add(new Student(3, "li", "13499230340"));
GenericList.Iterator<Student> iter = list.getIterator();
while (iter.hasNext()) {
Student s = iter.next();
System.out.println(s);
}
// GenericList<Teacher> list = new GenericList<Teacher>();
// list.add(new Teacher("赵","语文"));
// list.add(new Teacher("李","数学"));
// list.add(new Teacher("张","英语"));
//
// GenericList.Iterator<Teacher> iter = list.getIterator();
// while (iter.hasNext()){
// Teacher t = iter.next();
// System.out.println(t);
// }
}
}