以下是一个可以正确执行的代码- import java.util.*;
- import java.io.*;
- class Student implements Comparable<Student>
- {
- private String name;
- private int en,cn,ma;
- private int sum;
- Student(String name,int en,int cn,int ma)
- {
- this.name=name;
- this.en=en;
- this.cn=cn;
- this.ma=ma;
- sum=en+cn+ma;
- }
- public String getSum()
- {
- return this.name;
- }
- public int compareTo(Student stu)
- {
- if(this.sum==stu.sum)//为什么可以stu.sum而不报错?sum不是私有变量吗?why?
- return this.name.compareTo(stu.name);
- return this.sum-stu.sum;
- }
- public int hashCode()
- {
- return name.hashCode()+sum*36;
- }
- public boolean equals(Object obj)
- {
- if(obj instanceof Student)
- return false;
- Student s=(Student)obj;
-
- return s.name.equals(this.name) && s.sum==this.sum;
- }
- public String toString()
- {
- return "student"+"["+name+","+ma+","+en+","+cn+","+sum+"]";
- }
- }
- class StudentTool
- {
- public static Set<Student> getStudents() throws IOException
- {
- Set<Student> set=new TreeSet<Student>();
- BufferedReader bufr=
- new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- while((line=bufr.readLine())!=null)
- {
- if("over".equals(line))
- break;
- String[] info=line.split(",");
-
- Student s=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
-
- set.add(s);
- }
-
- bufr.close();
- return set;
- }
- public static void write2File(Set<Student> stu) throws IOException
- {
- BufferedWriter bw=new BufferedWriter(new FileWriter("student.txt"));
- for(Student s : stu)
- {
- bw.write(s.toString()+"\t");
- bw.write(s.getSum());
- bw.newLine();
- bw.flush();
- }
- bw.close();
- }
- }
- class StudentsIOTest
- {
- public static void main(String[] args) throws IOException
- {
- Set<Student> ts=StudentTool.getStudents();
- StudentTool.write2File(ts);
- }
- }
复制代码 正如代码里我注释的那样- public int compareTo(Student stu)
- {
- if(this.sum==stu.sum)//为什么可以stu.sum而不报错?sum不是私有变量吗?why?
- return this.name.compareTo(stu.name);//这个也是
- return this.sum-stu.sum;//这个也是!!
- }
复制代码 为什么没报错?在这列为什么对象可以直接调用私有变量?!!百思不得其解啊!!!
|