黑马训练营——毕向东老师的一个题目。。。有点不明白
//hashCode方法是有什么作用?
//如何比较的?原理
Comparator<Students> cmp = Collections.reverseOrder();
package Demo;
import java.io.*;
import java.util.*;
public class StudentsInfo {
/**
* 有五个学生,每个学生三门课成绩
* 如 zhangsan,30,90,97
* 计算出总成绩并从高到低排序后保存到文件中 stuinfo.txt
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//如何比较的?
Comparator<Students> cmp = Collections.reverseOrder();
Set stus = StudentinfoTool.getStudents(cmp);
StudentinfoTool.WriteTofile(stus);
}
}
class StudentinfoTool
{
public static Set<Students> getStudents()
{
return getStudents(null);
}
public static Set<Students> getStudents(Comparator<Students> cmp)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Students> stus = null;
if (cmp==null)
stus = new TreeSet<Students>();
else
stus = new TreeSet<Students>(cmp);
try {
while ((line=br.readLine()) != null)
{
if (line.equals("over"))
{
break;
}
String []arr = line.split(",");
Students stu = new Students(arr[0], Integer.parseInt(arr[1]),
Integer.parseInt(arr[2]) , Integer.parseInt(arr[3]));
stus.add(stu);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return stus;
}
public static void WriteTofile(Set<Students> stus)
{
BufferedWriter bw=null;
try {
bw = new BufferedWriter(new FileWriter("D:\\stuinfo.txt"));
for (Students stu : stus)
{
bw.write(stu.toString()+"\t");
bw.write(stu.getSum()+"");
bw.newLine();
bw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Students implements Comparable<Students>
{
private String name;
private int ma,cn,en;
private int sum;
Students(String name,int ma,int cn,int en)
{
this.name = name;
this.ma = ma;
this.cn = cn;
this.en = en;
sum = ma + cn + en;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
//hashCode方法是有什么作用?
public int hashCode()
{
return name.hashCode()+sum*78;
}
public boolean equals(Object obj)
{
if (! (obj instanceof Students))
throw new ClassCastException("数据类型不匹配");
Students s = (Students)obj;
return this.name.equals(s.name) && this.sum==s.sum;
}
public String toString()
{
return "Student["+name+", "+ma+", "+cn+", "+en+"]";
}
@Override
public int compareTo(Students s) {
// TODO Auto-generated method stub
int num = new Integer(this.sum).compareTo(new Integer(s.sum));
if (num==0)
return this.name.compareTo(s.name);
return num;
}
}
|
|