一、实验目的
本次实验的主要目的是练习在程序中应用
Java
特殊类和泛型进行程序设计,
熟悉内部类、集合类、字符串和泛型的基础知识,掌握应用内部类、集合类、字
符串和泛型完成程序设计的基本方法。
二、实验要求
- 认真阅读实验内容,完成实验内容所设的题目。
- 能够应用多种编辑环境编写Java语言源程序。
- 认真体会Java语言特殊类和泛型的概念。
- 将实验结果书写在实验报告中。
三、实验内容
运行下列程序,观察程序的运行结果
A、程序一
public class Fyt {
public static void main(String[] args) {
Parcel p = new Parcel();
p.testShip();
Parcel.Contents c = p.new Contents(33);
Parcel.Destination d = p.new Destination( "Hawii" );
p.setProperty( c, d );
p.ship();
}
}
class Parcel {
private Contents c;
private Destination d;
class Contents {
private int i;
Contents( int i ){ this.i = i; }
int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) {label = whereTo;}
String readLabel() { return label; }
}
void setProperty( Contents c, Destination d ){
this.c =c; this.d = d;
}
void ship(){
System.out.println( "move "+ c.value() +" to "+ d.readLabel() );
}
public void testShip() {
c = new Contents(22);
d = new Destination("Beijing");
ship();
}
}
主类
Fyt
:
- 在
main
方法中创建了一个Parcel
对象p
,调用其testShip
方法。- 接着,创建了
Parcel
的Contents
和Destination
的实例,并通过setProperty
方法设置它们。- 最后调用
ship
方法来展示运输的内容。public class Fyt { public static void main(String[] args) { Parcel p = new Parcel(); p.testShip(); Parcel.Contents c = p.new Contents(33); Parcel.Destination d = p.new Destination("Hawii"); p.setProperty(c, d); p.ship(); } }
类
Parcel
:
- 定义了两个私有成员变量
c
和d
,分别用于存储Contents
和Destination
的实例。- 定义了内部类
Contents
:
- 具有一个私有整型变量
i
,构造函数用于初始化i
。value
方法返回i
的值。class Parcel { private Contents c; private Destination d; class Contents { private int i; Contents(int i) { this.i = i; } int value() { return i; } }
内部类
Destination
:
- 具有一个私有字符串变量
label
,构造函数初始化label
。readLabel
方法返回label
的值。class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return label; } }
方法
setProperty
和ship
:
setProperty(Contents c, Destination d)
方法用于设置Contents
和Destination
的实例。ship()
方法输出运输的信息,例如将内容移至目的地。void setProperty(Contents c, Destination d) { this.c = c; this.d = d; } void ship() { System.out.println("move " + c.value() + " to " + d.readLabel()); }
测试运输的方法
testShip
:
testShip()
方法实例化了Contents
和Destination
,然后调用ship()
方法,展示运输的内容。public void testShip() { c = new Contents(22); d = new Destination("Beijing"); ship(); } }
B、程序二
package org.example; public class Main { public static void main(String[] args) { { Circle circle = new Circle(10); circle.Showdraw(); } } static class Circle { private double radius = 0; public static int count = 1; public Circle(double radius) { this.radius = radius; } public void Showdraw() { Draw draw = new Draw(); draw.drawSahpe(); } class Draw { public void drawSahpe() { System.out.println(radius); System.out.println(count); } } } }
主类
Main
:
- 在
main
方法中创建Circle
的实例circle
,并调用其Showdraw
方法来展示圆的半径和计数。public class Main { public static void main(String[] args) { Circle circle = new Circle(10); circle.Showdraw(); } }
类
Circle
:
- 包含一个私有属性
radius
表示圆的半径,初始化为 0。- 定义了一个公共静态变量
count
,初始化为 1。- 通过构造函数初始化
radius
的值。static class Circle { private double radius = 0; public static int count = 1; public Circle(double radius) { this.radius = radius; }
方法
Showdraw
:
- 在
Showdraw
方法中,创建一个Draw
的实例,并调用其drawShape
方法。public void Showdraw() { Draw draw = new Draw(); draw.drawSahpe(); }
内部类
Draw
:
Draw
内部类包含一个方法drawShape
,该方法输出Circle
的radius
和count
的值。class Draw { public void drawSahpe() { System.out.println(radius); System.out.println(count); } }
C、程序三
package org.example; public class Main { public static void main(String[] args){ Object obj = new Outer().makeTheInner(47); System.out.println("Hello World!" + obj.toString()); } }class Outer { private int size = 5; public Object makeTheInner(int localVar) { final int finalLocalVar = 99; class Inner{ public String toString(){ return("InnerSize:" + size + "localVar:" + localVar + "finalLocalVar:" + finalLocalVar); } } return new Inner(); } }
主类
Main
:
- 在
main
方法中,创建一个Outer
类的实例,并调用makeTheInner
方法生成Inner
类的实例。- 打印输出一个字符串,包含了内部类
Inner
重写的toString()
方法的返回值。public class Main { public static void main(String[] args) { Object obj = new Outer().makeTheInner(47); System.out.println("Hello World!" + obj.toString()); } }
外部类
Outer
:
- 定义一个私有实例变量
size
,初始化为 5。makeTheInner
方法接受一个整型参数localVar
,并在方法中声明一个final
变量finalLocalVar
,初始化为 99。- 在
makeTheInner
方法中,定义了一个内部类Inner
。class Outer { private int size = 5; public Object makeTheInner(int localVar) { final int finalLocalVar = 99; // 声明 final 局部变量 class Inner { public String toString() { return ("InnerSize:" + size + " localVar:" + localVar + " finalLocalVar:" + finalLocalVar); } } return new Inner(); // 返回 Inner 的实例 } }
内部类
Inner
:
- 在
Inner
类中重写了toString()
方法,以返回包含size
、localVar
和finalLocalVar
值的字符串。
D、程序四
package org.example; public class Main { public static void main(String[] args){ Outer outer=new Outer(); Object o=outer.makeTheInner(20); System.out.println(o); } } class Outer { private int size = 5; public Object makeTheInner(int localVar) { final int finalLocalVar = 99; return new Object(){ public String toString(){ return ("InnerSize:" + size + "finalLocalVar:" + finalLocalVar+" localVar:"+localVar); } }; } }
主类
Main
:
- 在
main
方法中,创建一个Outer
类的实例outer
。- 调用
outer
的makeTheInner
方法,并传入参数20
,返回一个对象o
。- 输出这个对象
o
,该对象包含了重写的toString()
方法。public class Main { public static void main(String[] args) { Outer outer = new Outer(); Object o = outer.makeTheInner(20); System.out.println(o); } }
外部类
Outer
:
- 定义一个私有实例变量
size
,初始化为5
。makeTheInner
方法接收一个整型参数localVar
,并声明一个final
局部变量finalLocalVar
,初始化为99
。- 在这个方法内部,创建并返回一个匿名内部类对象,并重写其
toString()
方法。class Outer { private int size = 5; public Object makeTheInner(int localVar) { final int finalLocalVar = 99; return new Object() { public String toString() { return ("InnerSize: " + size + " finalLocalVar: " + finalLocalVar + " localVar: " + localVar); } }; } }
E、程序五
package org.example; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class Main { public static void main(String[] args) { String aString = "A", bString = "B", cString = "C", dString = "D", eString = "E"; List<String> list = new LinkedList<>(); // 创建集合 list.add(aString); list.add(bString); list.add(eString); // 输出语句,用迭代器 Iterator<String> iter = list.iterator(); // 创建集合迭代器 while(iter.hasNext()) { // 遍历集合中的元素 System.out.print(iter.next() + " "); } System.out.println(); // 换行 list.set(1, cString); // 将索引位置1的对象修改为对象bString Iterator<String> it = list.iterator(); while(it.hasNext()) { System.out.print(it.next() + " "); } } }
F、程序六
package org.example; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { DAO<User> dao = new DAO<User>(); dao.map = new HashMap<String,User>(); dao.save("1001", new User(1, 32, "梁朝伟")); dao.save("1002", new User(2,34,"汤唯")); dao.save("1003", new User(3,23,"刘嘉玲")); User u = dao.get("1002"); System.out.println(u); dao.update("1002", new User(4,45,"成龙")); dao.delete("1003"); List<User> list = dao.list(); System.out.println(list); }} class DAO<T> { Map<String,T> map; public void delete(String id){ map.remove(id); } public List<T> list(){ List<T> list = new ArrayList<T>(); for(String s : map.keySet()){ list.add(map.get(s)); } return list; } public void update(String id,T entity){ map.put(id, entity); } public T get(String id){ return map.get(id); } public void save(String id,T entity){ map.put(id, entity); } } class User { private int id;private int age; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User(int id, int age, String name) { super(); this.id = id; this.age = age; this.name = name; } @Override public String toString() { return "User [id=" + id + ", age=" + age + ", name=" + name + "]"; }@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (age != other.age) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
主类
Main
:
- 在
main
方法中,创建了一个DAO<User>
的实例。- 使用
save
方法添加几个用户到HashMap
中。- 使用
get
方法根据 ID 获取用户,并打印用户信息。- 使用
update
方法更新用户信息。- 使用
delete
方法删除一个用户。- 获取所有用户的列表并打印。
public class Main { public static void main(String[] args) { DAO<User> dao = new DAO<>(); dao.map = new HashMap<>(); dao.save("1001", new User(1, 32, "梁朝伟")); dao.save("1002", new User(2, 34, "汤唯")); dao.save("1003", new User(3, 23, "刘嘉玲")); User u = dao.get("1002"); System.out.println(u); dao.update("1002", new User(4, 45, "成龙")); dao.delete("1003"); List<User> list = dao.list(); System.out.println(list); } }
DAO 类
DAO<T>
:
- 使用
Map<String, T>
存储数据实体。- 提供了 CRUD 操作的方法:
save(String id, T entity)
:保存实体。get(String id)
:根据 ID 获取实体。update(String id, T entity)
:根据 ID 更新实体。delete(String id)
:根据 ID 删除实体。list()
:返回所有实体的列表。class DAO<T> { Map<String, T> map; public void delete(String id) { map.remove(id); } public List<T> list() { List<T> list = new ArrayList<>(); for (String s : map.keySet()) { list.add(map.get(s)); } return list; } public void update(String id, T entity) { map.put(id, entity); } public T get(String id) { return map.get(id); } public void save(String id, T entity) { map.put(id, entity); } }
用户类
User
:
- 包含用户属性:
id
、age
和name
,并提供相应的 getter 和 setter 方法。- 提供构造函数初始化用户信息。
- 重写
toString
方法用于打印用户信息。- 重写
hashCode
和equals
方法,提供对象的统一性和比较标准。class User { private int id; private int age; private String name; // Constructors, getters, and setters... @Override public String toString() { return "User [id=" + id + ", age=" + age + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { // Equals implementation... } }
四、编写程序完成下列功能
1.使用Map集合统计字符串中“123, 456, 789, 123, 456”中每个整数出现的次
数并打印出来。
package org.example; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.HashMap; public class Main { public static void main(String[] args) { String input = "123, 456, 789, 123, 456"; String[] numbers = input.split(",\\s*"); HashMap<String, Integer> countMap = new HashMap<>(); for (String number : numbers) { if (countMap.containsKey(number)) { countMap.put(number, countMap.get(number) + 1); } else { countMap.put(number, 1); } } for (String number : countMap.keySet()) { System.out.println(number + ": " + countMap.get(number)); } } }
2. 定义一个Father和Child类,并进行测试。
要求如下:
Father类为外部类,类中定义一个私有的String类型的属性name,name的值
为“zhangjun”。
Child类为Father类的内部类,其中定义一个introFather()方法,方法中调用
Father类的name属性。
定义一个测试类Test,在Test类的main()方法中,创建Child对象,并调用
introFather ()方法。
public class Main { private String name = "fyt"; public String getName() { return name; } public class Child { public void introFather() { System.out.println("Father's name is " + Main.this.getName()); } } } public class Test { public static void main(String[] args) { Main main = new Main(); Main.Child child = main.new Child(); child.introFather(); } }
3.声明一个泛型类:zhui(锥),表示锥型,并定义一个求锥型体积的方法,
编写程序分别输出圆锥和方锥的体积。
注:锥型体积等于底面积和高的乘积。
package org.example; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.HashMap; public class Main<T extends Number> { private T bottomArea; private T height; public Main(T bottomArea, T height) { this.bottomArea = bottomArea; this.height = height; } public double getVolume() { return bottomArea.doubleValue() * height.doubleValue() / 3; } public static void main(String[] args) { // 圆锥底面积为半径r的圆的面积,高为h Main<Double> circularCone = new Main<>(Math.PI * Math.pow(2.0, 2.0), 5.0); System.out.println("The volume of circular cone is: " + circularCone.getVolume()); // 方锥底面积为边长为a的正方形的面积,高为h Main<Integer> squareCone = new Main<>(4, 6); System.out.println("The volume of square cone is: " + squareCone.getVolume()); } }
五、实验总结
在本次实验中,我通过设计学生信息管理系统,深入学习了Java特殊类和泛型的应用。通过实践,我掌握了内部类、集合类、字符串和泛型的基础知识,并学会了如何巧妙地运用它们进行程序设计。这次实验让我更加熟练地使用集合类存储和操作数据,以及利用泛型实现灵活的操作方法。