---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------
注册三天可算能发文章了 哦也! 补上补上 这是第一篇...
首先有toString() 然后是get() set() 其次是hashCode() equals()和实现Comparable的compartTo()
import java.util.*;
class Student implements Comparable<Student>
{
private int age;
private String name;
private String city;
Student(int age,String name,String city)
{
this.age=age;
this.name=name;
this.city=city;
}
public int hashCode()
{
return name.hashCode()+city.hashCode()+age*17;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
return false;
Student s=(Student)obj;
return this.name.equals(s.name)&&this.age==s.age&&this.city.equals(s.city);
}
public int compareTo(Student stu)
{
int num=age-stu.age;
if(num==0)
{
int namenum=this.name.compareTo(stu.name);
if(namenum==0)
return city.compareTo(stu.city);
return namenum;}
return num;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public String getCity()
{
return city;
}
public String toString()
{
return age+name+city;
}
}
有了这些 就可以在Treeset 集合中排序了.....
class practice14
{
public static void main(String[] args)
{
TreeSet<Student> ts=new TreeSet<Student>();
ts.add(new Student(17,"ok","aj"));
ts.add(new Student(17,"ok","bj"));
for(Student s:ts)
{
System.out.println(s);
}
}
}
---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------
黑马程序员_自定义学生类需要的几个必备的方法
最新推荐文章于 2023-04-17 13:15:24 发布