Is Java always new?

Is there any way in Java that looks like

Thing thing = new Thing();

cannot lead to the creation of a new object (i.e. how thingcan it point to an existing object)?

+5
source share
12 answers

The statement newallocates new heap space and calls the constructor. You will always receive a new object this way (if, as others have pointed out, an exception is thrown in the constructor).

The thing is slightly different from static methods that return a link, for example Integer.valueOf(), which, if possible, reuses objects from the internal pool.

+16
source

Thing , . thing Thing.

+6

, , . , . :

public class Test {
    static int count;

    static Set<Test> set = new HashSet<Test>();

    int id = count++;


    public Test() {
        set.add(this);
        throw new RuntimeException();
    }


    public static void main(String[] args) throws Exception {
        for(int i = 0; i < 5; i++) {
            try {
                new Test();
            } catch(Exception e) {
            }
        }
        System.out.println(set);
    }


    public String toString() {
        return "Test[" + id + "]";
    }
}

:

[Test[0], Test[1], Test[2], Test[4], Test[3]]

new .

+4

new , . , , , . . String interning Java.

+3

(, ), , (singleton, factory, pool ..).

+1

, , OutOfMemoryError.

, , Thing.

0

, .

new - .

, , , .

this ( - this = oldObject ), - , .

0

, ++, operator new . ( JLS)

0

new . java , . java. . Boolean class (true false), , .

0

.

thing , .

0

new , , , , . , , , , ClassNotFound websphere. , websphere - .

0

In Java, the only thing I can think of is to use the Singleton pattern. This would not create several new Thing instances, but rather an instance of the same object each time.

-1
source

All Articles