日期:2014-05-20 浏览次数:20726 次
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Test { public static void main(String[] args) { Set<Element> set = new HashSet<Element>(); Element i1 = new Element(1); Element i2 = new Element(2); Element i3 = new Element(3); set.add(i1); set.add(i2); set.add(i3); System.out.println("Before changed:"); printSet(set); i1.setValue(2); System.out.println(i1.equals(i2)); System.out.println("After changed:"); printSet(set); } public static void printSet(Set set) { Iterator it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } class Element { private int value; public Element(int value) { this.value = value; } public void setValue(int value) { this.value = value; } public int getValue() { return this.value; } @Override public String toString() { return "" + this.value; } @Override public boolean equals(Object obj) { if(this ==(Element)obj) return true; if (!(obj instanceof Element)) { return false; } if (((Element) obj).getValue() == this.getValue()) { return true; } return false; } @Override public int hashCode() { return 37 + this.value; } }