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)形式;
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)形式;
相关文章推荐
- java集合Set的应用(HashSet、Tree…
- HashSet的hashCode方法和equals方法的重写,TreeSet中compareTo方法的重写,Comparator在treeSet中的应用。
- HashSet和TreeSet中最好只放入不可变对象
- Java数据结构与算法之数据结构-逻辑结构-集合(七)------集合之Set接口和HashSet和TreeSet、LinkedHashSet实现类总结
- HashSet和TreeSet 分别实现对象的排序操作
- List.HashMap.TreeMap.HashSet,TreeSet以及集合排序
- JCF treeset的用法实例
- HashSet 与TreeSet和LinkedHashSet的区别
- list,set,map应用实例
- 反射应用实例--根据map中的值创建对应并调用set方法给域赋值
- [TreeMap和TreeSet]——简单应用
- TreeSet与排序_实践应用,TreeSet显示某商品的若干信息
- ADA Ⅱ型数 STL-set实例应用
- Collection TreeSet TreeMap排序 ArrayList HashSet去重之间的区别
- HashSet和TreeSet及修改其判断方法
- java集合类(七)Iterator应用实例
- java集合类深入分析之TreeMap/TreeSet篇
- Java TreeSet 应用
- Uva 10815 安迪的第一个字典 set数组应用实例
- Java集合框架:Set(HashSet,LinkedHashSet,TreeSet)