#Java泛型类。,
分享于 点击 48780 次 点评:264
#Java泛型类。,
编写一个学校School泛型类和一个班级Class泛型类,编写一个学生Student普通类。三个类之间的关系是:学校里有多个班级,班级里有多个学生。使用泛型类嵌套泛型类的方式实现以上场景。
代码如下:
package com.homework.lhh;
public class Ex05 {
public static void main(String[] args) {
/*
* Students stu = new Students("小怪兽", 18); Class<Students> cla = new
* Class<Students>(stu); School<Class<Students>> sho = new
* School<Class<Students>>(cla);
* System.out.println(sho.getData().getData().toString());
*/
//设置班级数,以及班级中学生信息
Students[] class01 = { new Students("小怪兽", 18, 1001), new Students("奥特玛", 17, 1002),
new Students("伊丽莎白", 18, 1003), new Students("山鸡", 19, 1004), new Students("威廉姆斯", 18, 1005) };
Students[] class02 = { new Students("小小", 18, 1006), new Students("嗷嗷", 17, 1007), new Students("依依", 18, 1008),
new Students("吉吉", 19, 1009), new Students("微微", 18, 1010) };
Students[] class03 = { new Students("兽兽", 18, 1011), new Students("特特", 17, 1012), new Students("丽丽", 18, 1013),
new Students("姗姗", 19, 1014), new Students("思思", 18, 1015) ,new Students("奥利奥", 17, 1016)};
//用一个班级信息的数组存放所有的班级
@SuppressWarnings({ "unchecked", "rawtypes" })
Class<Students>[] classinfo = new Class[] { new Class(class01), new Class(class02), new Class(class03) };
//用一个学校的数组显示所有的班级
@SuppressWarnings({ "unchecked", "rawtypes" })
School<Class<Students>> school = new School(classinfo);
int num = 0;
for (int i = 0; i < school.getArray().length; i++) {
System.out.println("第" + (i + 1) + "班学生信息为:");
num = 0;
for (int j = 0; j < school.getArray()[i].getArray().length; j++) {
System.out.println(school.getArray()[i].getArray()[j]);
num++;
}
System.out.println((i + 1) + "班一共有" + num + "名学生");
System.out.println();
}
}
}
class School<T> {
T[] array;
public T[] getArray() {
return array;
}
public void setArray(T[] array) {
this.array = array;
}
public School(T[] array) {
super();
this.array = array;
}
}
class Class<T> {
T[] array;
public Class(T[] array) {
super();
this.array = array;
}
public T[] getArray() {
return array;
}
public void setArray(T[] array) {
this.array = array;
}
}
class Students {
private String name;
private int age;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public Students(String name, int age, int id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
@Override
public String toString() {
return "姓名:" + name + "\t年龄:" + age + "岁\t学号:" + id;
}
}
运行结果如下:
相关文章
- 暂无相关文章
用户点评