package com.broadengate.fangxing;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;/** * 應該都知道 hashset 不允許放入重複的資料,那麼他是根據什麼來判斷是否是重複的資料呢? * 在hashset中用到了hash演算法,因為hashset底層也是用的Hashmap來存取資料 * ,在hashmap底層則是用的數組來存取,而在hashmap放資料的時候會用到hashcode * ,這就是hashmap存入的資料沒有順序的原因,他就是根據hashcode來存放的 * * 如果不重寫hashcode 則預設是使用Object裡面的,是根據對象的引用地址來產生的hashcode,所以在沒建立一個對象的時候他的引用地址都不一樣, * */public class HashCodeTest {public static void main(String[] args) {HashCodeTest hashCodeTest = new HashCodeTest();Collection coll = new /* ArrayList() */HashSet();Person person = hashCodeTest.new Person("1", 1);Person person1 = hashCodeTest.new Person("1", 1);Person person2 = hashCodeTest.new Person("1", 1);Person person3 = hashCodeTest.new Person("1", 1);Person person4 = hashCodeTest.new Person("1", 1);Person person5 = hashCodeTest.new Person("1", 1);coll.add(person5);coll.add(person4);coll.add(person);coll.add(person2);coll.add(person3);coll.add(person1);// 如果重寫了hashcode方法和eq方法, 如果這裡把放入記憶體中的對象的值改變,則他的hashcode值就會變,// jvm在根據hashcode算出來的地區去找person對象就找不到那個對象,所以就不能移除person.setAge(2);coll.remove(person);System.out.println(coll.size());}class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}/** * @Override public int hashCode() { final int prime = 31; int result = * 1; result = prime * result + getOuterType().hashCode(); * result = prime * result + age; result = prime * result + * ((name == null) ? 0 : name.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; Person other = (Person) obj; * if (!getOuterType().equals(other.getOuterType())) return * false; if (age != other.age) return false; if (name == * null) { if (other.name != null) return false; } else if * (!name.equals(other.name)) return false; return true; } * * private HashCodeTest getOuterType() { return * HashCodeTest.this; } **/}}