Set接口

来源:互联网 发布:苹果手机网络时间校准 编辑:程序博客网 时间:2024/05/20 11:50
  1. 实现set接口的集合是无序的,且元素不允许重复相同,这里的重复相同主要体现在这个equals()方法和hashcode()方法。
    关于equals()方法和hashcode()方法的详细介绍链接

    2.`
    import java.util.HashSet;
    import java.util.Iterator;

public class SetTest {

public static void main(String[] args) {    // TODO Auto-generated method stub    HashSet<AboutSet> hs=new HashSet<AboutSet>();    hs.add(new AboutSet(111));    hs.add(new AboutSet(222));    hs.add(new AboutSet(333));    hs.add(new AboutSet(444));    hs.add(new AboutSet(555));    System.out.println("hs:"+hs);    Iterator<AboutSet> iter=hs.iterator();    AboutSet ab=(AboutSet)iter.next();    ab.setCount(111);    System.out.println("hs:"+hs);    hs.remove(new AboutSet(111));    System.out.println("hs:"+hs);    System.out.println("是否有222:"+hs.contains(new AboutSet(222)));    System.out.println("是否有111:"+hs.contains(new AboutSet(111)));}

}

class AboutSet
{
private int count;

public AboutSet(int count){    this.count=count;}public int getCount() {    return this.count;}public void setCount(int count) {    this.count = count;}@Overridepublic int hashCode() {    final int prime = 31;    int result = 1;    result = prime * result + count;    return result;}@Overridepublic boolean equals(Object obj) {    if (this == obj)        return true;    if (obj == null)        return false;    if (getClass() != obj.getClass())        return false;    AboutSet other = (AboutSet) obj;    if (count != other.count)        return false;    return true;}/* (non-Javadoc) * @see java.lang.Object#toString() */@Overridepublic String toString() {    return "R["+this.count+"]";}

}

  1. 重写equals() hashcode()使得值与hashcode值绑定了,但是在Hashset中这样使用容易导致无法正确访问对象,上面就是一个例子。
0 0
原创粉丝点击