黑马程序员技术交流社区
标题:
TreeSet排序的问题。。。
[打印本页]
作者:
黑马任雪刚
时间:
2012-5-28 20:25
标题:
TreeSet排序的问题。。。
import java.io.*;
import java.util.*;
//需求是:在控制台上输入几个学生的姓名,数学,语文成绩,并计算出总成绩,最后安总成绩从高到低排好存入到文件中。
//问题:在学生工具类中已经用TreeSet对学生对象进行了自动排序,为什么学生类还要继承Compareble呢???????
//建立学生类
class Student implements Comparable<Student>
{
private String name;
private int num;
private int cn;
private int sn;
Student(String name,int cn,int sn)
{
this.name=name;
this.cn=cn;
this.sn=sn;
num=cn+sn;
}
public int getNum()
{
return num;
}
public String toString()
{
return "["+this.name+","+this.cn+","+this.sn+"]";
}
public int hashCode()
{
return name.hashCode()+num*70;
}
public int compareTo(Student s)
{
int nu=new Integer(this.num).compareTo(new Integer(s.num));
if(nu==0)
return this.name.compareTo(s.name);
return nu;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配!");
Student s = (Student)obj;
return this.name.equals(s.name)&&this.num==s.num;
}
}
class studentTool //建立学生工具类。
{
public static Set<Student> Student() throws IOException
{
return studentinfo(null);
}
public static Set<Student> studentinfo(Comparator<Student> cmp)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
Set<Student> st = null;
if(cmp==null)
st = new TreeSet<Student>();
else
st = new TreeSet<Student>(cmp);
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
else
{
String[] info=line.split(",");
Student s = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]));
st.add(s);
}
}
br.close();
return st;
}
public static void xieru(Set<Student> s)throws IOException
{
BufferedWriter bw = new BufferedWriter(new FileWriter("bbb.txt"));
for(Student s1:s)
{
bw.write(s1.toString()+"\t");
bw.write(s1.getNum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
public class Bl
{
public static void main(String[] args) throws IOException
{
Comparator<Student> cmp = Collections.reverseOrder();
Set<Student> se = studentTool.studentinfo(cmp);
studentTool.xieru(se);
}
}
作者:
张晨
时间:
2012-5-28 21:11
因为继承Compareble,所以treeSet才知道怎么给学生类排序呀,要不然学生类中有年龄,姓名,这些按照谁排呢
作者:
高云飞
时间:
2012-5-28 21:17
因为,之所以TreeSet能够对对象排序,是因为排序的根据是该类中compareTo方法的返回值,所以必须要求Person类实现Comparable接口,复写其compareTo方法,这样,向TreeSet中传入person对象才知道排序的依据了。这称为自然排序。
当然也可以用自定义的比较类,实现Compartor接口,复写compare方法,然后向TreeSet中传入person的时候,同时传入你的自定义比较类的实例化对象。
TreeSet<Person> ts = new TreeSet<Person>(new 自定义比较类);
作者:
袁梦希
时间:
2012-5-28 21:58
首先我来回答楼主的
疑问,我就不写复杂的代码了。
楼主的提的问题就问错了,应该是实现Compareble,不是继承,
在向TreeSet中存储元素的时候,TreeSet会使用指定的比较算法对存储元素进行排序, 内部以二叉树形式进行存储.
当对(对象)进行排序的时候,也就是对Student对象排序的时候,需要实现Comparable接口,重写compareTo方法,
在方法中定义比较算法,比如是按名字排序,按成绩排序,或者按某一科成绩排序,如果不实现实现Comparable接口,根本做不到
这么详细的排序,他是自然顺序。
备注:另外还有一种传入一个比较器的方法,比较器顺序: 定义类实现Comparator接口, 重写compare方法, 创建比较器对象, 传入TreeSet构造函数.
Comparator接口只是优先Comparable接口罢了,如果楼主想深刻探讨,加好友就可以,
说的不是很专业,希望我的回答能解决问题。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2