Java Base == & equals

 

Tags:  Integer cache, == , equals

This Blogger emphasizes that in actual development, developers should prioritize using .equals() to compare object values ​​rather than simply relying on == to compare references.

Java's Integer cache mechanism provides memory optimization for Java programs with values ​​in the range of -128 to 127.However, values ​​outside this range will result in the creation of new objects, resulting in unexpected results in == comparisons. 

    public static void main(String[] args) {

        Integer a = 228;
        Integer b = 228;
        System.out.println(a == b); // false

        Integer x = 1;
        Integer y = 1;
        System.out.println(x == y); // true

        Integer c = 228;

        Integer d = 228;
        System.out.println(System.identityHashCode(c)); //  1795799895
        System.out.println(System.identityHashCode(d)); // 1698097425

        Integer e = 1;
        Integer f = 1;
        System.out.println(System.identityHashCode(e)); // 1376400422
        System.out.println(System.identityHashCode(f)); // 1376400422

    }

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE