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

Java_浅谈集合中自定义元素排序方式

2014-07-13 19:49 417 查看
1.当集合定义的是HashSet类型时,元素类中要重写的方法有两个,分别是public int hashCode()和public boolean equals(Object obj),这两个方法用于保证元素唯一性。

如下所示:

class Student{

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 hashCode(){

return name.hashCode()+age*34;

}

public boolean equals(Object obj){

if(!(obj instanceof Student)){

throw new ClassCastException("类型不匹配");

}

Student stu=(Student)obj;

return this.name.equals(stu.name)&&this.age==stu.age;

}

}

注意:HashSet中元素是无序的,哈希表是无序的。

2.当HashSet集合元素可能用于二叉树集合时,要实现Comparable接口进行默认的排序。代码示例如下:

class Student implements Comparable<Student>{

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 hashCode(){

return name.hashCode()+age*34;

}

public boolean equals(Object obj){

if(!(obj instanceof Student)){

throw new ClassCastException("类型不匹配");

}

Student stu=(Student)obj;

return this.name.equals(stu.name)&&this.age==stu.age;

}

public int compareTo(Student stu){

int num=new Integer(age).compareTo(new Integer(stu.age));

if(num==0){

return name.compareTo(stu.name);

}

return num;

}

}

也就是说,基于二叉树数据结构的集合元素类可以通过实现Comparable接口,复写public int compareTo(Object obj)方法来完成默认排序的功能。

更多内容更新,待续。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: