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

java集合类(五)HashSet与TreeSet应用实例

2011-04-26 16:41 393 查看
(1)HashSet(散列表)应用(里面不能有相同的元素,当元素为对象时,需重写hashCode与equals方法)

import java.util.*;

public class text1 {

public static void ptintElements(Collection c)

{

Iterator i=c.iterator();

while(i.hasNext())

System.out.println(i.next());

}

public static void main(String[] args)

{

text1 t=new text1();

Student s1=new Student(4,"qy");

Student s2=new Student(2,"kng");

Student s3=new Student(3,"lk");

Student s4=new Student(2,"ji");

Student s5=new Student(2,"zhag");

Student s6=new Student(2,"zhag");

HashSet h=new HashSet();

h.add(s1);

h.add(s2);

h.add(s3);

h.add(s4);

h.add(s5);

h.add(s6);

t.ptintElements(h);

}

}

class Student {

int num;

String name;

Student(int num,String name)

{

this.name=name;

this.num=num;

}

public int hashCode()

{

return num*(name.hashCode());

}

public boolean equals(Object o)

{

Student s=(Student)o;

return num==s.num&&name.equals(s.name);

}

public String toString()

{

return num+" "+name;

}

}

(2)TreeSet应用(TreeSet内的元素以升序排列,当元素为对象时,需要传递一个比较器)

采用TreeSet t=new TreeSet(Comparator)形式;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: