java Set

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;
}
@Override
public String toString() {
return no +" "+ name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((no == null) ? 0 : no.hashCode());
return result;
}
@Override
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 (no == null) {
if (other.no != null)
return false;
} else if (!no.equals(other.no))
return false;
return true;
}

}

 

posted @ 2022-03-15 17:41  不会一直是菜鸟  阅读(98)  评论(0)    收藏  举报