- import java.util.*;
- import java.io.*;
- //为了使其属性具备比较性要实现Comparable接口
- class Student implements Comparable
- {
- private String name;
- private int ma,cn,en;//ma:数学,cn:语文 en:英语
- private int sum;//sum:总成绩
- public Student(String name,int ma,int cn,int en){
- this.name=name;
- this.ma=ma;
- this.cn=cn;
- this.en=en;
- sum=ma+cn+en;
- }
- //覆盖compareTo方法:
- public int compareTo(Object obj){
- Student s=(Student)obj;//强转
- int num=new Integer(this.sum).compareTo(new Integer(s.sum));//比较总分数
- if(num==0){
- //如果总分数相等就比较姓名
- return this.name.compareTo(s.name);
- }
- return num;
- }
- public int hashCode(){
- return name.hashCode()+sum*78;
- }
- public boolean equals(Object obj){
- if(!(obj instanceof Student)){
- throw new ClassCastException("类型不匹配");
- }
- Student s=(Student)obj;
- return this.name.equals(s.name)&&this.sum==s.sum;
- }
- public String toString(){
- return "String["+name+","+ma+","+cn+","+en+"]";
- }
- public String getName(){
- return name;
- }
- public int getMa(){
- return ma;
- }
- public int getCn(){
- return cn;
- }
- public int getEn(){
- return en;
- }
- public int getSum(){
- return sum;
- }
- }
- //定义工具类
- class StudentInfoTool
- {
- public static Set<Student>getStudents()throws IOException{
- //键盘录入
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- //创建集合对象
- Set<Student> stus=new TreeSet<Student>();
- while((line=bufr.readLine())!=null){
- if("over".equals(line)){
- break;
- }
- String []info=line.split(",");//以“,”来切割键盘输入的数据
- Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
- stus.add(stu);//将对象存到集合
- }
- bufr.close();
- return stus;//返回集合
- }
- //将集合中的数据写到文件中
- public static void write2File(Set<Student> stus)throws IOException{
- BufferedWriter bfs=new BufferedWriter(new FileWriter("d:\\123.txt"));
- for(Student s:stus){
- bfs.write(s.getName());
- bfs.write(+s.getMa()+"");
- bfs.write(s.getCn()+"");
- bfs.write(s.getEn()+"");
- bfs.write(s.getSum()+"");
- bfs.newLine();
- bfs.flush();
- }
- bfs.close();
- }
- }
- class StudentInfoTest
- {
- public static void main(String[] args) throws IOException
- {
- Set<Student> stu=StudentInfoTool.getStudents();
- StudentInfoTool.write2File(stu);
- }
- }
复制代码
这个代码我有三个地方不明白,Student类中为什么要覆盖hashCode和equals方法,干什么用?还有就是,覆盖的toString方法,怎么感觉没有调用呢,没按着toString的格式写入? |