-1

In Java, why this

int n = 100000;
int[] array = new int[n + n / 2];
int[] arrayzip = new int[n];
System.arraycopy(array, 0, arrayzip, 0, n);
hashmap.put(x, arrayzip);

and this

int n = 100000;
int[] array = new int[n + n / 2];
hashmap.put(x, new int[n]);
System.arraycopy(array, 0, hashmap.get(x), 0, n);

take the same amount of memory? In the first code sample an extra array is created.

[EDIT] Alright, now the second question:

for (int i = 0; i < 100; i++) {
    int n = 100000;
    int[] array = new int[n + n / 2];
    int[] arrayzip = new int[n];
    System.arraycopy(array, 0, arrayzip, 0, n);
    hashmap.put(x, arrayzip);
}

What if we put any sample of code inside a loop, then arrayzip is created 100 times and then all 100 references are gone due to being scoped in a loop. Aaa, now I understand, so objects new int[] are created on the heap but they are not lost (garbage collected) because they stored their references in a out-of-scope object hashmap. Cool, I understand!

4

1 に答える 1

10

No, both samples create the same number of arrays - 2. They both contain the following array creation expressions:

new int[n + n / 2]
new int[n]

Where did you think another array was being created? Or had you not spotted the array creation expression in the second case, within this statement:

hashmap.put(x, new int[n]);

The fact that in the first version the reference to one of them is assigned to a local variable makes no difference in terms of how many objects are created.

(I'd personally vastly prefer the first code over the second, by the way. It's much simpler to understand, IMO.)

于 2013-03-20T19:41:45.797 に答える