package j2se.basicKnowledge.exercises; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Test4_Collection { /*★★★★★★ * hashCode的算法:简单的说hashCode是根据每个对象的‘内存区域的值’和对象的‘内容的哈希值’比较的; * 由于‘内容相同’的对象但其‘内存地址’不同,计算出来的hashCode就‘不会相同’ * * hashMap的作用:它将‘相同hashCode值’的对象都放在‘相同的内存区域‘中,当有元素要往Set中插入时,底层的hashMap会找到与【此元素】’哈希值相同‘的 * 内存区域的对象与之比较,然后看有没有内容与之相同的对象;这样就提高了查找的速度 * *重写了Object类的equals()方法的类,惯例上都要重写hashCode(),使equals的2个对象其hashCode 也要相同 *注意:只有’要放入哈希表‘中的类对象才’需要重写hashCode()‘ */ static int a; //全局变量不用先初始化就可以使用,而局部变量必须先初始化才能使用?试试把变量a放到方法中声明且先不初始化就使用会报错吗? public static void main(String[] args) { //★★★在没有重写Object类的equals()的类中:从以下实验可以看出比较'集合'中的元素是否相等,比较的是2元素是否equals(),即比较2元素是否”==“; //★★★String类是比较特殊的,他重写了Object类的equals()和hashCode(),只要是'内容'相等的对象,其hashCode也相等 //★★★但是,测试下Person类--它没有重写Object类的equals()和hashCode(),看结果怎么样? //但是Person类像String类重写equals()和hashCode()方法后,结果应该和String一样 Set j1 = new HashSet(); //List j1 = new ArrayList(); String s1 = new String("a"); String s2 = new String("a"); Person p1 = new Person("huzong",28); Person p2 = new Person("huzong",28); Person p3 = new Person("huzong",28); j1.add("8"); j1.add(s1); j1.add(s2); System.out.println(j1.size()); j1.add(p1); j1.add(p2); //注意:下面3行代码是实验JAVA中一种'内存泄露'的情况,将p1的值更改后,是不能将它从集合中移除的,这样p1就一直存在于集合中了;这就是JAVA中内存泄露的一种情况! p1.age=25; j1.remove(p1); System.out.println("j1中还存在p1吗?"+j1.contains(p1)); System.out.println(j1.size()); System.out.println("s1.hashCode()==s2.hashCode():"+(s1.hashCode()==s2.hashCode())); System.out.println("s1.equals(s2):"+s1.equals(s2)); System.out.println("p1.hashCode()==p2.hashCode():"+(p1.hashCode()==p2.hashCode())); System.out.println("p1.equals(p2):"+p1.equals(p2)); System.out.println("String类型的8与int类型的8 equals吗?:"+j1.contains(8));//contains其实调用了2个对象的equals()和hashCode()类比较两对象是否相同;String类型的"8"与int 8的equals和hashCode当然不同了 System.out.println("Stirng类型s2没有add进集合j1中,那么j1.contains(s2)吗?:"+j1.contains(s2)); System.out.println("自定义person类型p3没有add进集合j1中,那么j1.contains(p3)吗?:"+j1.contains(p3)); System.out.println(j1.size()); for (Object k : j1) { System.out.println(k);//从输出可以看出Set中的元素是无序的 } } } class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString (){ return this.name+this.age; } /*@Override public int hashCode() { final int prime = 31; int result = 1; 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; final Person other = (Person) obj; 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; }*/ }