package cn.itcast.demo;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
class Student{
private int age;
private String name;
public Student(int age,String name)
{
this.age = age;
this.name = name;
}
//要显示Student类的信息,必须重写toString 方法
public String toString(){
return "age :"+age+" name:"+name;
}
public int hashCode()
{
return age*name.hashCode();
}
public boolean equals(Object o){
Student s = (Student) o;
return age == s.age && name.equalsIgnoreCase(s.name);
}
}
public class HashSetTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加的String对象,不需要进行重写------------------------------
HashSet hs1 = new HashSet();
hs1.add("zxx");
hs1.add("zahx");
hs1.add("zyj");
hs1.add("xmh");
hs1.add("zah");
Iterator it = hs1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//-----------------------------------------------------
//如果添加的是一个自定的对象-------------------------------------
HashSet hs = new HashSet();
hs.add(new Student(28,"zah"));
hs.add(new Student(31,"xmh"));
hs.add(new Student(30,"zyj"));
hs.add(new Student(28,"zah"));
hs.add(new Student(33,"zxx"));
Student a1 = new Student(34,"dxx");
Student a11 = new Student(35,"dxx");
System.out.println("a1code"+a1.hashCode());
System.out.println("a11code"+a11.hashCode());
//--------------------------心血来潮的一个测试
String str1 ="abc";
String str2 ="abc";
System.out.println("str1"+str1.hashCode());
System.out.println("str2"+str2.hashCode());
//-------------------------------------
hs.add(null);
hs.add(null);
Iterator it1 = hs.iterator();
while(it1.hasNext())
{
System.out.println(it1.next());
}
//-----------------------------------------------------
LinkedHashSet linkHashSet = new LinkedHashSet();
Student linkedstu1 = new Student();
linkHashSet.add(linkedstu1);
}
}
测试发现HashSet添加的时候无序,而且不能重复加入
运行效果如图: