本帖最后由 歌诗王道 于 2014-4-12 13:26 编辑
hashSet里的元素都是无序的,不允许重复,为什么在hashSet里添加字符串可以直接去重,添加对象时却还要复写hashCode方法和equals方法?
- class HashSetDmeo
- {
- pubic static void sop(Object obj)
- {
- System.out.println(obj);
- }
-
- public static void main(String[] args)
- {
- HashSet hs = new HashSet();
- hs.add("tom");
- hs.add("jerry");
- hs.add("marry");
- hs.add("tom");
- Iterator it = hs.iterator();
- while(it.hasNext())
- {
- sop(it.next());
- }
- HashSet hs2 = new HashSet();
- hs2.add("new Person("tom"));
- hs2.add("new Person("jerry"));
- hs2.add("new Person("marry"));
- hs2.add("new Person("tom"));
- Iterator it2 = hs2.iterator();
- while(it2.hasNext())
- {
- Person p = (Person)it.next;
- sop(p.getName());
- }
- }
-
- }
- class Person
- {
- private String name;
- Person(String name)
- {
- this.name = name;
- }
- public String getName()
- {
- return name;
- }
-
- public static int hashCode()
- {
- return 60;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Person))
- return false;
- Person p = (Person)obj;
- return this.name.equals(p.name);
- }
-
- }
复制代码
|