//HashSet的不能重复性
import java.util.HashSet;
public class SetTest1
{
public static void main(String[] args)
{
HashSet set = new HashSet();
//HashSet不能重复添加相同对象
System.out.println(set.add("a"));
set.add("b");
set.add("c");
set.add("d");
System.out.println(set.add("a"));
System.out.println(set);
}
}
输出结果:
true
false
[d, b, c, a]
//HashSet的插入的各种注意事项:在集合当中hashcode()和equals()方法是分不开的
public class SetTest2
{
public static void main(String[] args)
{
HashSet set = new HashSet();
// set.add(new People("zhangsan"));
// set.add(new People("lisi"));
// set.add(new People("zhangsan"));
// People p1 = new People("zhangsan");
//
// set.add(p1);
// set.add(p1);
String s1 = new String("a");
String s2 = new String("a");
System.out.println("hash code: " + (s1.hashCode() == s2.hashCode()));
set.add(s1);
set.add(s2);
System.out.println(set);
}
}
class People
{
String name;
public People(String name)
{
this.name = name;
}
}
//自定义和eclipse自动生成的hashcode()方法和equals()方法,原理都是一样的
public class SetTest3
{
public static void main(String[] args)
{
HashSet set = new HashSet();
Student s1 = new Student("zhangsan");
Student s2 = new Student("zhangsan");
set.add(s1);
set.add(s2);
System.out.println(set);
}
}
class Student
{
String name;
public Student(String name)
{
this.name = name;
}
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
// public int hashCode()
// {
// return this.name.hashCode();
// }
//
// public boolean equals(Object obj)
// {
// if(this == obj)
// {
// return true;
// }
//
// if(null != obj && obj instanceof Student)
// {
// Student s = (Student)obj;
//
// if(name.equals(s.name))
// {
// return true;
// }
// }
//
// return false;
// }
}
//HashSet中迭代Iterator方法的介绍
import java.util.HashSet;
import java.util.Iterator;
public class InteratorTest
{
public static void main(String[] args)
{
HashSet set = new HashSet();
set.add("a");
set.add("b");
set.add("c");
set.add("d");
set.add("e");
// Iterator iter = set.iterator();
//
// while(iter.hasNext())
// {
// String value = (String)iter.next();
// System.out.println(value);
// }
for(Iterator iter = set.iterator(); iter.hasNext(); )
{
String value = (String)iter.next();
System.out.println(value);
}
}
}