Java - String pool

public static void main(String[] args) {
    String one = "hello";
    String two = "hello";

    if (one == two) {
        System.out.println("they are the same objects");
    } else {
        System.out.println("they are different objects");
    }

    String three = new Integer(76).toString();
    String four = "76";

    if (three == four) {
        System.out.println("they are the same objects");
    } else {
        System.out.println("they are different objects");
    }

    String five = new Integer(76).toString().intern();
    String six = "76";

    if (three == four) {
        System.out.println("they are the same objects");
    } else {
        System.out.println("they are different objects");
    }
}

控制台打印结果:

they are the same objects
they are different objects
they are the same objects

Actually, modern virtual machines are very efficient and clever. And if they detect that an object you're creating is not going to be shared, that is, it doesn't go outside the code block in which it's created, then the virtual machine will in fact create that object on the stack. We won't see it and it won't impact anything we write.

Although Java doesn't give us any control over where objects are created, the virtual machine, in reality, makes the most efficient choice for us. So our code will generally run in an optimized way. 

Java hasn't been able to reuse the string it created for object three for object four. That's because the string for object three did not get virtual machine to place that string in the pool.

Java will automatically place little strings into the pool anyway, so it's only these calculated strings that aren't placed in the pool.

Now, the reason to use intern is that, of course, it's better for any strings that are going to be reused a lot to be in the pool, as this will minimize the number of objects created and needing to be garbage collected.

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/114257820