Java随机4-Hashset

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; }
		 **/

	}
}

posted @ 2011-10-24 22:26  常伟华  阅读(726)  评论(0编辑  收藏  举报