您的位置:首页 > 编程语言 > Java开发

java基础入门----TreeSet练习1

2013-10-02 15:18 453 查看
import java.util.*;

//set:元素是无序的,元素不能重复
//hashset:底层数据是哈希表结构
//TreeSet:可对set集合中元素进行排序
//       第一种排序方式:让元素自身具备比较性,元素需要实现comparable接口,覆盖compareTo方法,return 0 就是元素重复了 保证了唯一性
//       第二种排序方式:当元素自身不具备比较性或者所具备的比较性不是需要的   就要通过TreeSet的构造函数传入新的比较器

//需求1:自定义学生对象    按年龄排序   年龄相同就看次要条件姓名
class TreeSet1
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student("sgrg",12));
ts.add(new Student("vfs",13));
ts.add(new Student("bbb",13));
ts.add(new Student("bbb",20));
ts.add(new Student("ccc",14));

Iterator it = ts.iterator();

while(it.hasNext())
{
Student s = (Student)it.next();
sop(s.getName()+"..."+s.getAge());
}
}
}

class Student implements Comparable //该接口强制让学生具备比较性   这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
{
private String name;
private int age;
Student(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");

Student s = (Student)obj;

System.out.println(this.name+"..compare.."+s.name);

if(this.age > s.age)
return 1;
if(this.age == s.age)
return this.name.compareTo(s.name);  //string本身定义了compareTo方法,有默认顺序
return -1;
}
}

class MyCompare implements Comparator   //需求改变了,按姓名排序//这种方法更好
{
public int compare(Object obj1, Object obj2)
{
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
int num = s1.getName().compareTo(s2.getName());
if(num==0)
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
/*
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge())
return 0;
return -1;
*/
}
return num;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: