博主
258
258
258
258
专辑

第六节 常用类

亮子 2021-09-10 18:30:59 4052 0 0 0

1)、Object

(1)equals和==的区别

public class ObjectApplication {

    public static void main(String[] args) {

        //--1
        Integer a = 100;
        Integer b = 100;

        System.out.println(a==b);
        System.out.println(a.equals(b));

        //--2
        Integer x = 500;
        Integer y = 500;

        System.out.println(x==y);
        System.out.println(x.equals(y));
    }
}

(2)hashCode

两个相等对象的equals方法一定为true, 但两个hashcode相等的对象不一定是相等的对象。

相同的对象hashcode一定是相同的。不同的对象hashcode有可能相同。

2)、String

(1)hashCode碰撞问题

public class StringHashCode {

    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        List<String> list = Arrays.asList("Aa", "BB", "C#");
        for(String s: list) {
            System.out.println(s.hashCode());

            map.put(s, s.hashCode());
        }
        System.out.println(map);
    }
}