package com.bfd; import java.util.HashSet; public class Demo01 { public static void main(String[] args) { /*1.什么原因导致Set集合元素不重复 * 1.实现的数据结构导致的-hashtable * 通过 集合元素的hashCode方法 分配在那条链表或者红黑树上 * 通过 集合元素的equals方法,判断链表或集合中是否已存在此元素 * 2.Object的hashCode方法为:public native int hashCode(); 对象内存地址的h整数值 * 3.Object的equals方法为:return (this == obj); * 4.String的hashCode * * */ //"哈希冲突"问题 System.out.println("重地".hashCode()); System.out.println("通话".hashCode()); //String的哈希算法 char[] val = new String("重地").toCharArray(); int h = 0; for (int i = 0; i < "重地".length(); i++) { h = 31 * h + val[i]; } System.out.println(h); //31*37325+22320 System.out.println(‘重‘ + 0);//37325 System.out.println(‘地‘ + 0);//22320 System.out.println(31 * 37325 + 22320); //36890+31*35805+35805 System.out.println(‘通‘ + 0);//36890 System.out.println(‘话‘ + 0);//35805 System.out.println(31 * 36890 + 35805); System.out.println("=====测试hash冲突=========="); //模拟哈希冲突 HashSet set = new HashSet<>(); System.out.println(set.add(new Person("张飞",18))); System.out.println(set.add(new Person("关羽",22))); System.out.println(set.size()); } } class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; if (age != person.age) return false; return name != null ? name.equals(person.name) : person.name == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } /* @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { return true; }*/ }
package com.bfd; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.HashSet; import java.util.Iterator; public class Demo01 { public static void main(String[] args) { /*1.什么原因导致hashset无序和linkedhashset有序呢? * 存放的顺序和hashcode的value有关,Integer的value是它的数值 * value/16就是它存放第几条链表的位置*/ HashSet hashset = new HashSet(); hashset.add(5); hashset.add(4); hashset.add(9); hashset.add(1); hashset.add(16); for (Object i : hashset ) { System.out.println(i); } //存放HashCode的值相同,就会存放在一条链表或者红黑树上 hashset.clear(); hashset.add(new Person("x", 1)); hashset.add(new Person("y", 2)); hashset.add(new Person("z", 4)); hashset.add(new Person("m", 3)); Iterator iterator = hashset.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } } class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int hashCode() { return 1; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
原文:https://www.cnblogs.com/bajiaotai/p/12989406.html