import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetDemos { public static void main(String[] args) { // 新建一个Set类的集合 Set st = new HashSet(); st.add("abc1"); st.add("abc2"); st.add("abc1"); st.add("abc2"); //输出结果只会有 abc1 和abc2 不允许元素重复 Iterator it = st.iterator(); while(it.hasNext()) { System.out.println(it.next()); } st.removeAll(st); st.add(new Studenti("lisi",23)); st.add(new Studenti("lisi",24)); st.add(new Studenti("lisan",22)); st.add(new Studenti("lisan",20)); Iterator its = st.iterator(); while(its.hasNext()) { Studenti s = (Studenti) its.next(); System.out.println(s.getName()+" "+s.getAge()); } } } class Studenti { private String name; private int age; Studenti(String name ,int age) { this.name=name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public String toString() { return "the student name : +name "+" and age is : "+ age; } public int hashCode() { return name.hashCode()+age*10; } public boolean equals(Object obj) { if(this == obj) return true ;//同一个对象放两次,直接返回true if(!(obj instanceof Studenti)) throw new ClassCastException("类型错误"); Studenti p = (Studenti)obj; return this .name.equals(p.name) && this.age == p.age; } }
运行程序:
原文地址:http://blog.csdn.net/zl18603543572/article/details/46555167