java Set
迭代器
迭代器相当于指针,常用next() hasNext()(返回布尔型)方法
HashSet<String> hs = new HashSet();
hs.add("hello");
hs.add("China");
hs.add("20");
Iterator it = hs.iterator();
while(it.hasNext())
{
String ss = (String)it.next();
if(ss.equals("China"))
it.remove();
}
往里面存一个数据,先看这个数据的hashCode(),如果没有元素跟它相同 就往里面存 否则就调用equals()判断,一般认为两个相同的数据(基本类型或者对象) hashCode和equals()都是一样的
HashSet hs = new HashSet();
System.out.println(hs);
Student s1 = new Student("1001","张三");
Student s2 = new Student("1002","李四");
Student s3 = new Student("1002","李四");
hs.add(s1);
hs.add(s2);
hs.add(s3);
System.out.println(hs);
如果王set里放的是自定义的对象 需要重写hashCode()、equals(),才能正常使用(从Source中重写)
class Student {
String no;
String name;
Student(String no,String name){
this.no = no;
this.name = name;
}

浙公网安备 33010602011771号