黑马程序员 集合ArrayList、HashSet和TreeSet的使用,hashsettreeset
分享于 点击 2360 次 点评:178
黑马程序员 集合ArrayList、HashSet和TreeSet的使用,hashsettreeset
---------------------- android培训、java培训、期待与您交流! ----------------------
ArrayList中对象比较只依赖于方法hashCode,可以有重复对象(排序)
HashSet和TreeSet中对象比较同时依赖于方法hashCode和equals,且不能有重复对象(无排序)。
现有需求要比较Student类中学生姓名和各科成绩总和,并且将成绩排序,需要用到有排序功能的集合,又要用到对象之间判断重复问题,所以我选择TreeSet,只有它具有这两样功能。具体办法是:Student类需要实现Comparable接口,并重写compareTo方法,这个方法用来比较大小,也就是二叉树原理。同时需要重写hashCode和equals方法,是为了高效快速的实现对象的比较。然后自定义一个比较器来给学生排序。然后将排序后的数据打印并保存到文件中,需要用到IO流。
hashCode和equals 方法:这两个方法是为了比较两个对象之间相同性,当两个对象比较时会先进入hashCode方法比较,如果两个对象的哈希地址不一样就不需要再比较了,如果一样,需要再进入equals方法比较,比较两个对象是否相同
compareTo方法:这个方法用来比较两个对象大小,所以,如果需要比较两对象大小,需要实现Comparable接口中compareTo方法,该方法返回int类型,可以由我们自己重写比较方法规则。
有了这些基础,做这个题目就容易多了。
import java.io.*;
import java.util.*;
class TreeSetDemo{
public static TreeSet<Student> getTreeSet(Comparator<Student> comp) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
TreeSet<Student> tree = new TreeSet<Student>(comp);
while((line=br.readLine())!=null)
{
if("over".equals(line))
return tree;
String[] arr = line.split(",");
Student stu = new Student(arr[0],Integer.parseInt(arr[1]),
Integer.parseInt(arr[2]),Integer.parseInt(arr[3]));
tree.add(stu);
}
return tree;
}
public static void main(String [] args) throws Exception
{
BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\stud.txt"));
//一般在对象无法比较的情况下加入自己添加的比较方法
//一般不轻易改动底层比较方法,而是采用添加接口比较
Comparator<Student> comp = Collections.reverseOrder();//将排序反转
Set<Student> set = TreeSetDemo.getTreeSet(comp);
for(Student st : set)
{
bw.write(st.toString()+"\t");
bw.write(st.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
class Student implements Comparable
{
private String name;
private int math,cn,en;
private int sum;
Student(String name,int math,int cn,int en)
{
this.name=name;
this.math=math;
this.cn=cn;
this.en=en;
this.sum=math+cn+en;
}
public String getName(){
return name;
};
public void setName(String name){
this.name=name;
}
public int getSum()
{
return sum;
}
public void setSum(int sum){
this.sum=sum;
}
public int hashCode()
{
return name.hashCode()+sum*37;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("不能比较对象");
Student stu = (Student)obj;
return name.equals(stu.getName())&&sum==stu.getSum();
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("不能转化为Student对象");
Student stu = (Student)obj;
int num = new Integer(this.sum).compareTo(new Integer(stu.getSum()));
if(num==0)
return name.compareTo(stu.getName());
return num;
}
public String toString()
{
return "[Student "+name+","+math+","+cn+","+en+"]";
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net/heima
相关文章
- 暂无相关文章
用户点评